﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using ERPStudio;
using System.Data.SqlClient;
using RelationTextBox;
using System.Text.RegularExpressions;
using System.Diagnostics;
using ExBug;
using System.Reflection;
using System.Threading;
using System.Globalization;

namespace ESRP
{
    public partial class RapoarteFrm : FrmRezumat
    {
        private CultureInfo cultureRO = new CultureInfo("ro-RO");
        private Int16 m_IdLista = -1;
        private Int16 TipLista = 0;
        private List<BindingSource> listBS = new List<BindingSource>();
        private List<SqlDataAdapter> listTA = new List<SqlDataAdapter>();
        public int AnulCurent = 0;
        public int LunaCurenta = 0;
        /// <summary>
        /// daca se foloseste documentul justificativ in nota contabila
        /// </summary>
        private Boolean bDocumentJustifRulaj = true;

        public RapoarteFrm(Int16 idLista,ModuleClass mInfo) : base(mInfo)
        {
            InitializeComponent();
            m_IdLista = idLista;
            _AllowAddRow = false;
            workConnString = mInfo.workConnectionString;
            EnableSearch = false;
            ActiveControl = valoriDGV;
            valoriDGV.Focus();
            HandleSalvare += new EventHandler(GenereazaLista);
        }

        private void RapoarteFrm_Load(object sender, EventArgs e)
        {

            SqlConnection wConn = DeschideConexiune(workConnString);
            SetCurentUnit(ModuleInfo.CodUnitate, wConn);
            this.listBndSourceMain.Add(paramListeBindingSource);
            this.listTableAdaptor.Add(this.paramListeTableAdapter.Adapter);

            
            AddButton("Genereaza", global::ERPStudio.Properties.Resources.salvare1, GenereazaLista, ToolStripItemAlignment.Right, true);

            Object ret = GetSetupValue("BalconSetup", "DocumentJustifRulaj", ModuleInfo.CodUnitate, wConn);
            Boolean val = false;
            if (ret == null || ret == DBNull.Value)
            {
                while (ret == null)
                {
                    SqlCommand comcfg = new SqlCommand("INSERT INTO BalconSetup (CodUnitate,AnCurent,LunaCurenta) VALUES (" + ModuleInfo.CodUnitate.ToString() + "," + DateTime.Now.Year.ToString() + "," + DateTime.Now.AddMonths(-1).Month.ToString() + ")",
                        wConn);
                    comcfg.ExecuteNonQuery();
                    ret = GetSetupValue("BalconSetup", "DocumentJustifRulaj", ModuleInfo.CodUnitate, wConn);
                }

            }
            val = (Boolean)ret;
            bDocumentJustifRulaj = val;

            #region Setare LiniiSemnatura diferit de null - genereaza eroare in rapoarte
            ret = GetSetupValue("BalconSetup", "LiniiSemnatura", ModuleInfo.CodUnitate, wConn);
            if (ret == null || ret == DBNull.Value)
            {
                SqlCommand comcfg = new SqlCommand("UPDATE BalconSetup  SET LiniiSemnatura=0 WHERE CodUnitate=" + ModuleInfo.CodUnitate.ToString(),
                    wConn);
                comcfg.ExecuteNonQuery();
            } 
            #endregion

            InchideConexiune(wConn);
            if (valoare2Column.Index < valoriDGV.ColumnCount && valoriDGV.RowCount>0)
                valoriDGV.CurrentCell = valoriDGV[valoare2Column.Index, 0];
           
        }

        private void RezumatConturi(object sender, EventArgs args)
        {
            FrmRezumat rez = null;
            if (ModuleInfo.AnArhiva != String.Empty)
            {
                rez = new ArhConturiRezumatFrm(ModuleInfo);
            }
            else
                rez = new ConturiRezumatFrm(ModuleInfo);

            rez.SelectionAddOn = true;
            if (rez.ShowDialog() == DialogResult.OK)
            {
                this.valoriDGV.CurrentCell.Value =
                    rez.selectedRow.Cells["ContColumn"].Value;
                if (this.valoriDGV.CurrentCell.IsInEditMode)
                    this.valoriDGV.EditingControl.Text = rez.selectedRow.Cells["ContColumn"].Value.ToString();        
            }
        }

        #region Rezumate
        private void RezumatJurnale(object sender, EventArgs args)
        {
            FrmMainMdi frm = MdiParent as FrmMainMdi;
            Assembly asm = frm.GetModule("erpforms");
            if (asm == null)
                return;

            String numeClasa = "ERPForms.JurnaleFrm";
            Type mModule = asm.GetType(numeClasa);

            if (mModule != null)
            {
                FrmRezumat newFrm = asm.CreateInstance(numeClasa, true, BindingFlags.Public | BindingFlags.Instance | BindingFlags.CreateInstance, null,
                   new object[] { ModuleInfo, true }, Thread.CurrentThread.CurrentCulture, new object[] { }) as FrmRezumat;

                newFrm.SelectionAddOn = true;
                if (newFrm.ShowDialog() == DialogResult.OK)
                {
                    this.valoriDGV.CurrentCell.Value =
                        newFrm.selectedRow.Cells["CodificareColumn"].Value;
                    if (this.valoriDGV.CurrentCell.IsInEditMode)
                        this.valoriDGV.EditingControl.Text = newFrm.selectedRow.Cells["CodificareColumn"].Value.ToString();
                }
            }

        }

        private void RezumatSurseFinantare(object sender, EventArgs args)
        {
            FrmRezumat rez = null;

            rez = new SurseFinantareFrm(ModuleInfo);

            rez.SelectionAddOn = true;
            if (rez.ShowDialog() == DialogResult.OK)
            {
                this.valoriDGV.CurrentCell.Value =
                    rez.selectedRow.Cells["CodColumn"].Value;
                if (this.valoriDGV.CurrentCell.IsInEditMode)
                    this.valoriDGV.EditingControl.Text = rez.selectedRow.Cells["CodColumn"].Value.ToString();
            }

        }

        private void RezumatArticol(object sender, EventArgs args)
        {

            FrmMainMdi frm = this.MdiParent as FrmMainMdi;
            Assembly asm = frm.GetModule("exbug");
            if (asm == null)
                return;

            String numeClasa = "ExBug.ArticoleAliniateFrm";
            Type mModule = asm.GetType(numeClasa);

            if (mModule != null)
            {
                FrmRezumat newFrm = asm.CreateInstance(numeClasa, true, BindingFlags.Public | BindingFlags.Instance | BindingFlags.CreateInstance, null,
                   new object[] { ModuleInfo }, Thread.CurrentThread.CurrentCulture, new object[] { }) as FrmRezumat;

                newFrm.SelectionAddOn = true;
                if (newFrm.ShowDialog() == DialogResult.OK)
                {
                    this.valoriDGV.CurrentCell.Value =
                        newFrm.selectedRow.Cells["ArtAlColumn"].Value;
                    if (this.valoriDGV.CurrentCell.IsInEditMode)
                        this.valoriDGV.EditingControl.Text = newFrm.selectedRow.Cells["ArtAlColumn"].Value.ToString();
                }
                newFrm.Close();
                newFrm.Dispose();

            }
        }

        private void RezumatMoneda(object sender, EventArgs args)
        {
            MessageBox.Show("Neimplementat");
        } 
        #endregion

        private void SaveLocal()
        {
            foreach (DataGridViewRow dr in valoriDGV.Rows)
            {
                Int16 RowIndex = (Int16)dr.Index;
                if (dr.Cells["tipColumn"].Value.ToString().Trim() == "S")
                {
                    dr.Cells["valoareColumn"].Value = dr.Cells["valoare2Column"].EditedFormattedValue.ToString();
                }
                if (dr.Cells["tipColumn"].Value.ToString().Trim() == "B")
                {

                    dr.Cells["valoareColumn"].Value = Convert.ToBoolean(dr.Cells["valoare2Column"].EditedFormattedValue) == true ? "1" : "0";
                    /*if (Convert.ToBoolean(dr.Cells["valoare2Column"].Value) == true)
                        dr.Cells["valoareColumn"].Value = "1";
                    else
                        dr.Cells["valoareColumn"].Value = "0";*/
                }
                if (dr.Cells["tipColumn"].Value.ToString().Trim() == "D")
                {
                    CultureInfo cultureRO = new CultureInfo("ro-RO");
                    if (dr.Cells["valoare2Column"].IsInEditMode)
                        dr.Cells["valoareColumn"].Value = (Convert.ToDateTime(dr.Cells["valoare2Column"].EditedFormattedValue)).ToOADate().ToString();
                    else
                        dr.Cells["valoareColumn"].Value = (Convert.ToDateTime(dr.Cells["valoare2Column"].EditedFormattedValue, cultureRO)).ToOADate().ToString();

                }
                if (dr.Cells["tipColumn"].Value.ToString().Trim() == "R")
                {
                    if (dr.Cells["valoare2Column"].Value == null)
                        dr.Cells["valoareColumn"].Value = String.Empty;
                    else
                        dr.Cells["valoareColumn"].Value = dr.Cells["valoare2Column"].EditedFormattedValue;
                }
                if (dr.Cells["tipColumn"].Value.ToString().Trim() == "T")
                {
                    dr.Cells["valoareColumn"].Value = dr.Cells["valoare2Column"].EditedFormattedValue;
                }
                //MessageBox.Show(dr.Cells["tipColumn"].Value.ToString());
            }

            base.Salvare(this, null);
        }
        /// <summary>
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        private void GenereazaLista(object sender, EventArgs args)
        {
            MyTrace("0-->>GenereazaLista");
            SaveLocal();
            ESRPDataSet eSRPDS = new ESRPDataSet();
            eSRPDS.EnforceConstraints = false;
            Cursor.Current = Cursors.AppStarting;
            String linia1 = String.Empty, linia2 = String.Empty;
            SqlCommand cmd = new SqlCommand("",DeschideConexiune(workConnString));


            PreviewRaportFrm frm = new PreviewRaportFrm("",null, ModuleInfo);
            //eSRPDataSet - este data setul cu care lucram

            foreach (BindingSource bs in listBS)
                if (bs != null) bs.Dispose();
            listBS.Clear();
            listBS.Add(new BindingSource(eSRPDS,"BalconSetup"));

            listTA.Clear();
            listTA.Add(new SqlDataAdapter("SELECT * FROM [BalconSetup] WHERE CodUnitate=" + ModuleInfo.CodUnitate.ToString(), cmd.Connection));
            listTA[0].SelectCommand.CommandType = CommandType.Text;

            listTA[0].Fill(eSRPDS.BalconSetup);
            DateTime dt = DateTime.Now,dte= new DateTime(DateTime.Now.Year,DateTime.Now.Month,1);

            String filtruTotal = String.Empty;
            switch (m_IdLista)
            { 
                
                case 1: //Balanta
                    Balanta(frm, eSRPDS);
                    break;
                case 2: //Fisa Cont
                    FisaCont(frm, eSRPDS);
                    break;
                case 3: //Cartea Mare
                    CarteaMare(frm, eSRPDS);
                    break;
                case 4: //Registru Jurnal
                    if (!RegistruJurnal(frm, eSRPDS))
                        return;
                    break;
                case 5: //Registru Casa
                    if (!RegistruCasa(frm, eSRPDS, "Registru de casa"))
                        return;
                    break;
                case 6: //Extras de cont
                    ExtrasDeCont(frm, eSRPDS, "Extras de cont");
                    break;
                case 7: //Extras de cont
                    ExtrasDeCont(frm, eSRPDS, "Fise generale");
                    break;
                case 9: //Extras de cont
                    MessageBox.Show("Lista nu este disponibila in aceasta versiune!");
                    return;
                case 10: //Operatiuni diverse
                    if (!OperatiuniDiverse(frm, eSRPDS))
                        return;
                    break;
                case 11: //Extras de cont
                    ExecutieCheltuieli(frm, eSRPDS);
                    break;
                case 12: //Extras de cont
                    if (!ListaOperatiuni(frm, eSRPDS))
                        return;
                    break;
                case 13: //Contul de executie al institutiilor publice
                    ExecutieCheltuieli(frm, eSRPDS);
                    break;
                case 8: //Bilant
                case 14: //Rezultat patrimonial
                case 15: //Venituri si cheltuieli
                    if (!Bilant(frm, eSRPDS))
                        return;
                    break;

            }
            foreach (SqlDataAdapter da in listTA)
                if(da!=null) da.Dispose();
            listTA.Clear();
            frm.MdiParent = this.MdiParent;
            frm.Show();
            cmd.Dispose();
            StudioForm.InchideConexiune(cmd.Connection);
            
            
            Cursor.Current = Cursors.Default;
            MyTrace("<<--oGenereazaLista");
        }

        public void balanta_dataloadHandler(object sender, Microsoft.Reporting.WinForms.SubreportProcessingEventArgs args)
        {
            ESRPDataSet eSRPDS = new ESRPDataSet();
            BindingSource bs = null;
            SqlDataAdapter ta = null;
            SqlConnection sqlConn = DeschideConexiune(workConnString);

            if (args.ReportPath == "SemnaturiSubReport")
            {
                bs = new BindingSource(eSRPDS, "Semnaturi");
                ta = new SqlDataAdapter("SELECT TOP 3 * FROM [Semnaturi] s JOIN [SemnaturiListe]  sl ON s.IDSemnatura=sl.IDSemnatura  WHERE sl.IDLista=" + m_IdLista.ToString() + " AND sl.[TipLista]=" + TipLista.ToString(), sqlConn);
                ta.Fill(eSRPDS.Semnaturi);
                args.DataSources.Add(new Microsoft.Reporting.WinForms.ReportDataSource("ESRPDataSet_Semnaturi", bs));
            }

            InchideConexiune(sqlConn);
            if(ta!=null)
                ta.Dispose();

        }

        public void FisaCont_dataloadHandler(object sender, Microsoft.Reporting.WinForms.SubreportProcessingEventArgs args)
        {
            ESRPDataSetListe eSRPDS = new ESRPDataSetListe();
            BindingSource bs = null;
            SqlDataAdapter ta = null;
            SqlConnection sqlConn = DeschideConexiune(workConnString);

            if (args.ReportPath == "SemnaturiSubReport")
            {
                bs = new BindingSource(eSRPDS, "Semnaturi");
                ta = new SqlDataAdapter("SELECT TOP 3 * FROM [Semnaturi] s JOIN [SemnaturiListe]  sl ON s.IDSemnatura=sl.IDSemnatura  WHERE sl.IDLista=" + m_IdLista.ToString() + " AND sl.[TipLista]=" + TipLista.ToString(), sqlConn);
                ta.Fill(eSRPDS.Semnaturi);
                args.DataSources.Add(new Microsoft.Reporting.WinForms.ReportDataSource("ESRPDataSet_Semnaturi", bs));
            
                InchideConexiune(sqlConn);
                if (ta != null)
                    ta.Dispose();
                return;

            }

            String cont = args.Parameters["cont"].Values[0];
            Decimal soldInitial = Convert.ToDecimal(args.Parameters["SoldPrecedent"].Values[0]);
            DateTime dld = DateTime.FromOADate(Convert.ToDouble(args.Parameters["DeLaData"].Values[0]));
            DateTime pld = DateTime.FromOADate(Convert.ToDouble(args.Parameters["PanaLaData"].Values[0]));
            bs = new BindingSource(eSRPDS, "balcon_GenNotaContabilaFC");
            this.balcon_GenNotaContabilaFCTableAdapter.Connection = sqlConn;
            this.balcon_GenNotaContabilaFCTableAdapter.Fill(eSRPDS.balcon_GenNotaContabilaFC,
                m_IdLista,
                cont,
                Convert.ToInt16(ModuleInfo.CodUnitate),
                dld,
                pld,
                (ModuleInfo.AnArhiva == String.Empty ? (Int16)0 : Convert.ToInt16(ModuleInfo.AnArhiva)),
                0,
                String.Empty,
                String.Empty);


            //for (int i = 0; i < bs.Count; i++)
            bs.Sort = "DataDoc";
            foreach(DataRowView drv in bs)
            {
                //ESRPDataSetListe.balcon_GenNotaContabilaFCRow dr = ((DataRowView)bs.List[i]).Row as ESRPDataSetListe.balcon_GenNotaContabilaFCRow;
                ESRPDataSetListe.balcon_GenNotaContabilaFCRow dr = drv.Row as ESRPDataSetListe.balcon_GenNotaContabilaFCRow;
                if(dr.ContDebit.Contains(cont))
                    soldInitial += dr.ValoareLei;
                else
                    if (dr.ContCredit.Contains(cont))
                        soldInitial -= dr.ValoareLei;

                dr.TipSold = (soldInitial >= 0) ? "D" : "C";
                dr.Sold = Math.Abs(soldInitial);
            }

            args.DataSources.Add(new Microsoft.Reporting.WinForms.ReportDataSource("ESRPDataSet_NotaContabilaView", bs));

            InchideConexiune(sqlConn);
            if (ta != null)
                ta.Dispose();
        }


        public void frm_dataloadHandlerCarteaMare(object sender, Microsoft.Reporting.WinForms.SubreportProcessingEventArgs args)
        {
            ESRPDataSetListe eSRPDS = new ESRPDataSetListe();
            BindingSource bs = null;

            DateTime dld = DateTime.FromOADate(Convert.ToDouble(args.Parameters["DeLaData"].Values[0]));
            DateTime pld = DateTime.FromOADate(Convert.ToDouble(args.Parameters["PanaLaData"].Values[0]));
            String contDebit = args.Parameters[0].Values[0];
            String contCredit = args.Parameters[1].Values[0];
            String debit = args.Parameters[2].Values[0];


            bs = new BindingSource(eSRPDS, "balcon_GenNotaContabila");
            SqlConnection sqlConn = DeschideConexiune(workConnString);
            this.balcon_GenNotaContabilaTableAdapter.Fill(eSRPDS.balcon_GenNotaContabila,
                m_IdLista,
                String.Empty,
                Convert.ToInt16(ModuleInfo.CodUnitate),
                dld,
                pld,
                (ModuleInfo.AnArhiva == String.Empty ? (Int16)0 : Convert.ToInt16(ModuleInfo.AnArhiva)),
                0,
                (debit == "True"?contDebit:String.Empty),
                (debit != "True"?contCredit:String.Empty));

            args.DataSources.Add(new Microsoft.Reporting.WinForms.ReportDataSource("ESRPDataSet_NotaContabilaView", bs));
            InchideConexiune(sqlConn);
        }


        public void frm_dataloadHandler(object sender, Microsoft.Reporting.WinForms.SubreportProcessingEventArgs args)
        {
            ESRPDataSet eSRPDS = new ESRPDataSet();
            BindingSource bs = null;
            SqlDataAdapter ta = null;
            SqlConnection sqlConn = DeschideConexiune(workConnString);

                if (args.ReportPath == "RegistruCasaSubreport" || args.ReportPath == "RegistruCasaCompactSubreport")
                {
                    Trace.Assert(args.Parameters.Count == 6, "Numar incorect de parametrii la subraport");
                    CultureInfo culture;
                    DateTimeStyles styles;
                    DateTime dateResult;

                    culture = Application.CurrentCulture;
                    styles = DateTimeStyles.None;

                    if (!DateTime.TryParse(args.Parameters["Data"].Values[0], culture, styles, out dateResult))
                        return;

                    bs = new BindingSource(eSRPDS, "NotaContabilaView");
                    ta = new SqlDataAdapter("GenNotaContabilaUnion", sqlConn);
                    ta.SelectCommand.CommandType = CommandType.StoredProcedure;
                    ta.SelectCommand.Parameters.Add(new SqlParameter("@cont", String.Empty));
                    ta.SelectCommand.Parameters.Add(new SqlParameter("@CodUnitate", ModuleInfo.CodUnitate));
                    ta.SelectCommand.Parameters.Add(new SqlParameter("@DeLaData", dateResult));
                    ta.SelectCommand.Parameters.Add(new SqlParameter("@PanaLaData", dateResult));
                    if (ModuleInfo.AnArhiva == String.Empty)
                        ta.SelectCommand.Parameters.Add(new SqlParameter("@An", Convert.ToInt16(0)));
                    else
                        ta.SelectCommand.Parameters.Add(new SqlParameter("@An", Convert.ToInt16(ModuleInfo.AnArhiva)));

                    ta.SelectCommand.Parameters.Add(new SqlParameter("@strFilter", FiltruRCDebit));
                    ta.SelectCommand.Parameters.Add(new SqlParameter("@strFilter2", FiltruRCCredit));
                    ta.SelectCommand.Parameters.Add(new SqlParameter("@strOrder", String.Empty));
                    ta.SelectCommand.Parameters.Add(new SqlParameter("@strFiltruNrNota", String.Empty));

                    ta.Fill(eSRPDS.NotaContabilaView);
                    args.DataSources.Add(new Microsoft.Reporting.WinForms.ReportDataSource("ESRPDataSet_NotaContabilaView", bs));

                }
            else
                if (args.ReportPath == "SemnaturiSubReport")
                {
                    bs = new BindingSource(eSRPDS, "Semnaturi");
                    ta = new SqlDataAdapter("SELECT TOP 3 * FROM [Semnaturi] s JOIN [SemnaturiListe]  sl ON s.IDSemnatura=sl.IDSemnatura  WHERE sl.IDLista=" + m_IdLista.ToString() + " AND sl.[TipLista]=" + TipLista.ToString(), sqlConn);
                    ta.Fill(eSRPDS.Semnaturi);
                    args.DataSources.Add(new Microsoft.Reporting.WinForms.ReportDataSource("ESRPDataSet_Semnaturi", bs));

                }

            InchideConexiune(sqlConn);
            if(ta!=null)
                ta.Dispose();
        }

        private Boolean OperatiuniDiverse(PreviewRaportFrm frm, ESRPDataSet eSRPDS)
        {
            SqlCommand cmd = new SqlCommand("", DeschideConexiune(workConnString));
            
            String objDte = String.Empty, filtruData = String.Empty;
            String linia1 = String.Empty, linia2 = String.Empty;
            DateTime dte = DateTime.Now, dt = DateTime.Now;

            cmd.CommandText = "SELECT [Valoare] FROM [ParamListe] WHERE COD='DLD' AND [User]=system_user AND [Host]=host_name() AND IDLista=" + m_IdLista.ToString() + " AND [CodUnitate]=" + ModuleInfo.CodUnitate.ToString();
            objDte = cmd.ExecuteScalar().ToString();
            filtruData = String.Empty;
            String filtruCat = String.Empty;
           if (objDte != String.Empty)
            {
                dte = DateTime.FromOADate(Convert.ToDouble(objDte));
                filtruData = " DataDoc >= @DataStart ";
            }


           cmd.CommandText = "SELECT [Valoare] FROM [ParamListe] WHERE COD='PLD' AND [User]=system_user AND [Host]=host_name() AND IDLista=" + m_IdLista.ToString() + " AND [CodUnitate]=" + ModuleInfo.CodUnitate.ToString();
            String objDt = cmd.ExecuteScalar().ToString();
            if (objDt != String.Empty)
            {
                dt = DateTime.FromOADate(Convert.ToDouble(objDt));
                if (filtruData != String.Empty)
                    filtruData += "AND ";
                filtruData += " DataDoc <= @DataEnd ";
            }


            cmd.CommandText = "SELECT [Valoare] FROM [ParamListe] WHERE COD='RGJ' AND [User]=system_user AND [Host]=host_name() AND IDLista=" + m_IdLista.ToString() + " AND [CodUnitate]=" + ModuleInfo.CodUnitate.ToString();
            Object obj = cmd.ExecuteScalar();
            String tipJurn = string.Empty;
            if(obj!=null)
                tipJurn = obj.ToString();

            if (tipJurn == "In afara bilantului")
                filtruCat = "[Categorie] = 2";
            else
                filtruCat = "[Categorie] = 0";

            cmd.CommandText = "SELECT [Valoare] FROM [ParamListe] WHERE COD='DTL' AND [User]=system_user AND [Host]=host_name() AND IDLista=" + m_IdLista.ToString() + " AND [CodUnitate]=" + ModuleInfo.CodUnitate.ToString();
            String centralizat = cmd.ExecuteScalar().ToString();
            if (centralizat == "Centralizat")
                centralizat = "True";
            else
                centralizat = "False";

            linia1 = "Operatiuni diverse " + tipJurn;
            linia1 += " in intervalul " + dte.ToString("d",cultureRO) + " - " + dt.ToString("d",cultureRO);

            cmd.CommandText = "SELECT [Valoare] FROM [ParamListe] WHERE COD='CTD' AND [User]=system_user AND [Host]=host_name() AND IDLista=" + m_IdLista.ToString() + " AND [CodUnitate]=" + ModuleInfo.CodUnitate.ToString();
            Object odlc = cmd.ExecuteScalar();
            String dlc = String.Empty;
            if (odlc != null) dlc = odlc.ToString();

            cmd.CommandText = "SELECT [Valoare] FROM [ParamListe] WHERE COD='CTC' AND [User]=system_user AND [Host]=host_name() AND IDLista=" + m_IdLista.ToString() + " AND [CodUnitate]=" + ModuleInfo.CodUnitate.ToString();
            Object oplc = cmd.ExecuteScalar();
            String plc = String.Empty;
            if (oplc != null)
                plc = oplc.ToString();

            if (plc != String.Empty && dlc != String.Empty)
            {
                MessageBox.Show("Lista nu poate fi generata pentru un cont debit si un cont credit simultan!", "Eorare",
                    MessageBoxButtons.OK, MessageBoxIcon.Stop);
                return false;
            }

            String filtruContDebit = String.Empty;
            String filtruContCredit = String.Empty;
            String filtruCont = String.Empty;
            if (plc != String.Empty || dlc != String.Empty)
            {

                if (dlc != String.Empty)
                {
                    linia2 = "pentru contul " + dlc;
                    filtruContDebit += "ContDebit Like '" + dlc + "%'";
                    filtruCont = " AND " + filtruContDebit;
                }
                if (plc != String.Empty)
                {
                    linia2 += " pentru contul " + plc;
                    filtruContCredit += "ContCredit LIKE '" + plc + "%'";
                    filtruCont = " AND " + filtruContCredit;
                }

            }
            cmd.CommandText = "SELECT [IDJurnal] FROM [ParamListe] a JOIN [Jurnale] b ON b.Codificare = LTRIM(RTRIM(a.[Valoare])) " +
                    "WHERE COD='JRN' AND [User]=system_user AND [Host]=host_name() AND IDLista=" + m_IdLista.ToString() + " AND a.[CodUnitate]=" + ModuleInfo.CodUnitate.ToString();

            String sJurnal = "-1";
            if (cmd.ExecuteScalar() != null)
                sJurnal = cmd.ExecuteScalar().ToString();

            listBS.Add(new BindingSource(eSRPDS, "NotaContabilaView"));
            String comanda = " AND  ContDebit<>'N/A' AND ContCredit<>'N/A'";
            String filtreTot = String.Empty;
            ///sectiunea de jurnale
            if (filtruCat != String.Empty)
            {
                filtreTot += " AND " + filtruCat;
            }


            //comanda += " ORDER BY " + (Debit == "Debit" ? "ContDebit" : "ContCredit");
            //listTA.Add(new SqlDataAdapter("SELECT * FROM BalantaView", cmd.Connection));

            SumDocFormula sdf = new SumDocFormula(cmd.Connection);
            if(dlc == String.Empty && plc==String.Empty)
                sdf.CalcSume(filtreTot, filtruContDebit, filtruContCredit, dte, dt, sJurnal, false, ModuleInfo);
            else
                sdf.CalcSume(filtreTot, filtruContDebit, filtruContCredit, dte, dt, sJurnal, true, ModuleInfo);

            if (sJurnal != "-1")
            {
                filtreTot += " AND [IdJurnal] = " + sJurnal;
                cmd.CommandText = "SELECT [Valoare] FROM [ParamListe] WHERE COD='JRN' AND [User]=system_user AND [Host]=host_name() AND IDLista=" + m_IdLista.ToString() + " AND [CodUnitate]=" + ModuleInfo.CodUnitate.ToString();
                linia2 += " pentru " + cmd.ExecuteScalar().ToString();
            }

            if (filtruCont != String.Empty)
            {
                filtreTot += filtruCont;
            }
            comanda += filtreTot;

            cmd.CommandText = "SELECT [Valoare] FROM [ParamListe] WHERE COD='FRM' AND [User]=system_user AND [Host]=host_name() AND IDLista=" + m_IdLista.ToString() + " AND [CodUnitate]=" + ModuleInfo.CodUnitate.ToString();
            String nrFormula = cmd.ExecuteScalar().ToString();
            if (nrFormula != String.Empty)
            {
                try
                {
                    comanda += " AND [NumarDoc] =" + Convert.ToDecimal(nrFormula).ToString();
                }
                catch
                {
                    MessageBox.Show("Nr. formula nu este numeric!","Eorare",
                        MessageBoxButtons.OK,MessageBoxIcon.Stop);
                    return false;
                }
            }

            cmd.CommandText = "SELECT [Valoare] FROM [ParamListe] WHERE COD='TPD' AND [User]=system_user AND [Host]=host_name() AND IDLista=" + m_IdLista.ToString() + " AND [CodUnitate]=" + ModuleInfo.CodUnitate.ToString();
            nrFormula = cmd.ExecuteScalar().ToString();
            if (nrFormula != String.Empty)
            {
                comanda += " AND [TipDocJust] ='" + nrFormula +"'";
            }

            cmd.CommandText = "SELECT [Valoare] FROM [ParamListe] WHERE COD='NRN' AND [User]=system_user AND [Host]=host_name() AND IDLista=" + m_IdLista.ToString() + " AND [CodUnitate]=" + ModuleInfo.CodUnitate.ToString();
            nrFormula = cmd.ExecuteScalar().ToString();
            if (nrFormula != String.Empty)
            {
                comanda += " AND [NumarNota] ='" + nrFormula +"'";
            }


            listTA.Add(new SqlDataAdapter("GenNotaContabila", cmd.Connection));
            
            listTA[listTA.Count - 1].SelectCommand.CommandType = CommandType.StoredProcedure;
            listTA[listTA.Count - 1].SelectCommand.Parameters.Add(new SqlParameter("@cont", String.Empty));
            listTA[listTA.Count - 1].SelectCommand.Parameters.Add(new SqlParameter("@CodUnitate", Convert.ToInt16(ModuleInfo.CodUnitate)));
            listTA[listTA.Count - 1].SelectCommand.Parameters.Add(new SqlParameter("@DeLaData", dte));
            listTA[listTA.Count - 1].SelectCommand.Parameters.Add(new SqlParameter("@PanaLaData", dt));
            if (ModuleInfo.AnArhiva == String.Empty)
                listTA[listTA.Count - 1].SelectCommand.Parameters.Add(new SqlParameter("@An", Convert.ToInt16(0)));
            else
                listTA[listTA.Count - 1].SelectCommand.Parameters.Add(new SqlParameter("@An", Convert.ToInt16(ModuleInfo.AnArhiva)));
            listTA[listTA.Count - 1].SelectCommand.Parameters.Add(new SqlParameter("@strFilter", comanda));
            listTA[listTA.Count - 1].SelectCommand.Parameters.Add(new SqlParameter("@strOrder", String.Empty));

            listTA[1].Fill(eSRPDS.NotaContabilaView);



            frm.NumeRaport = "OperatiuniDiverse.rdlc";
            frm.AddDataSource("ESRPDataSet_BalconSetup", listBS[0]);
            frm.AddDataSource("ESRPDataSet_NotaContabilaView", listBS[1]);
            frm.AddParameter("Linia1", linia1, true);
            frm.AddParameter("Linia2", linia2, true);

            frm.AddParameter("DebitInitial", sdf.debInit, true);
            frm.AddParameter("CreditInitial", sdf.creInit, true);
            frm.AddParameter("DebitPrecedent", sdf.debPrec, true);
            frm.AddParameter("CreditPrecedent", sdf.crePrec, true);
            frm.AddParameter("RulajDebit", sdf.rulajDeb, true);
            frm.AddParameter("RulajCredit", sdf.rulajCre, true);
            frm.AddParameter("TotalSumeDebit", sdf.totalDeb, true);
            frm.AddParameter("TotalSumeCredit", sdf.totalCre, true);
            frm.AddParameter("Centralizat", centralizat, true);

            //frm.AddParameter("Debit", Debit == "Debit" ? "True" : "False", true);
            frm.SetWindowFormat(true);
            return true;
        }

        private void ExtrasContCentralizat(PreviewRaportFrm frm, ESRPDataSet eSRPDS)
        {
            SqlCommand cmd = new SqlCommand("", DeschideConexiune(workConnString));
            cmd.CommandText = "SELECT [Valoare] FROM [ParamListe] WHERE COD='DLD' AND [User]=system_user AND [Host]=host_name() AND IDLista=" + m_IdLista.ToString() + " AND [CodUnitate]=" + ModuleInfo.CodUnitate.ToString();
            String objDte = cmd.ExecuteScalar().ToString(), filtruData = String.Empty;
            String  linia1 = String.Empty, linia2 = String.Empty;
            DateTime dte = DateTime.Now, dt = DateTime.Now;

            if (objDte != String.Empty)
            {
                dte = DateTime.FromOADate(Convert.ToDouble(objDte));
            }


            cmd.CommandText = "SELECT [Valoare] FROM [ParamListe] WHERE COD='PLD' AND [User]=system_user AND [Host]=host_name() AND IDLista=" + m_IdLista.ToString() + " AND [CodUnitate]=" + ModuleInfo.CodUnitate.ToString();
            String objDt = cmd.ExecuteScalar().ToString();
            if (objDt != String.Empty)
            {
                dt = DateTime.FromOADate(Convert.ToDouble(objDt));
                if (filtruData != String.Empty)
                    filtruData += "AND ";
            }
            linia1 = "Executia cheltuielilor centralizata ";
            linia1 += " in intervalul " + dte.ToString("d",cultureRO) + " - " + dt.ToString("d",cultureRO);

            cmd.CommandText = "SELECT [Valoare] FROM [ParamListe] WHERE COD='DLC' AND [User]=system_user AND [Host]=host_name() AND IDLista=" + m_IdLista.ToString() + " AND [CodUnitate]=" + ModuleInfo.CodUnitate.ToString();
            String dlc = cmd.ExecuteScalar().ToString();
            cmd.CommandText = "SELECT [Valoare] FROM [ParamListe] WHERE COD='PLC' AND [User]=system_user AND [Host]=host_name() AND IDLista=" + m_IdLista.ToString() + " AND [CodUnitate]=" + ModuleInfo.CodUnitate.ToString();
            String plc = cmd.ExecuteScalar().ToString();
            String filtruCont = String.Empty;
            if (plc != String.Empty || dlc != String.Empty)
            {
                if (dlc != String.Empty)
                {
                    linia2 = "de la contul " + dlc;
                }
                if (plc != String.Empty)
                {
                    linia2 += " pana la contul " + plc;
                }
            }
            cmd.CommandText = "SELECT [IDJurnal] FROM [ParamListe] a JOIN [Jurnale] b ON b.Codificare = LTRIM(RTRIM(a.[Valoare])) " +
                    "WHERE COD='JRN' AND [User]=system_user AND [Host]=host_name() AND IDLista=" + m_IdLista.ToString() + " AND a.[CodUnitate]=" + ModuleInfo.CodUnitate.ToString();

            String sJurnal = "-1";
            if (cmd.ExecuteScalar() != null)
                sJurnal = cmd.ExecuteScalar().ToString();

            listBS.Add(new BindingSource(eSRPDS, "ExcutieCheltuieliCentralizata"));
            String comanda = "[GenListaExecutieChelt]";
            /*if (filtruCont != String.Empty)
            {
                filtruCont = filtruCont.Replace("#Cont#", "[ArtAl]");
                comanda += filtruCont;
            }*/
            ///sectiunea de jurnale
            if (sJurnal != "-1")
            {
                //comanda += " AND  [IdJurnal] = " + sJurnal;
                cmd.CommandText = "SELECT [Valoare] FROM [ParamListe] WHERE COD='JRN' AND [User]=system_user AND [Host]=host_name() AND IDLista=" + m_IdLista.ToString() + " AND [CodUnitate]=" + ModuleInfo.CodUnitate.ToString();
                linia2 += " pentru " + cmd.ExecuteScalar().ToString();
            }
            
            //listTA.Add(new SqlDataAdapter("SELECT * FROM BalantaView", cmd.Connection));
            listTA.Add(new SqlDataAdapter(comanda, cmd.Connection));
            listTA[1].SelectCommand.CommandType = CommandType.StoredProcedure;
            listTA[1].SelectCommand.Parameters.Add(new SqlParameter("idLista","11"));
            listTA[1].Fill(eSRPDS.ExCheltCen);

            frm.NumeRaport = "ExecutieCheltCentralizata.rdlc";
            //frm.dataloadHandler += new LoadDataHandler(frm_dataloadHandler);
            frm.AddDataSource("ESRPDataSet_BalconSetup", listBS[0]);
            ///filtreaza totalul...
            ///se va genera in raport
            ///
            listBS[1].Filter = "[ArtAl]<>'0'";
            frm.AddDataSource("ESRPDataSet_ExcutieCheltuieliCentralizata", listBS[1]);
            frm.AddParameter("Linia1", linia1, true);
            frm.AddParameter("Linia2", linia2, true);
            frm.SetWindowFormat(true);
            InchideConexiune(cmd.Connection);
        }

        private void ExecutieCheltuieli(PreviewRaportFrm frm, ESRPDataSet eSRPDS)
        {
            TipLista = 0;
            SqlCommand cmd = new SqlCommand("", DeschideConexiune(workConnString));
            cmd.CommandText = "SELECT [Valoare] FROM [ParamListe] WHERE COD='DLD' AND [User]=system_user AND [Host]=host_name() AND IDLista=" + m_IdLista.ToString() + " AND [CodUnitate]=" + ModuleInfo.CodUnitate.ToString();
            String objDte = cmd.ExecuteScalar().ToString(), filtruData = String.Empty;
            String linia1 = String.Empty, linia2 = String.Empty;
            DateTime dte = DateTime.Now, dt = DateTime.Now;
            String capitol = String.Empty;

            if (objDte != String.Empty)
            {
                dte = DateTime.FromOADate(Convert.ToDouble(objDte));
                if (filtruData != String.Empty)
                    filtruData += " AND ";
            }

            cmd.CommandText = "SELECT [Valoare] FROM [ParamListe] WHERE COD='PLD' AND [User]=system_user AND [Host]=host_name() AND IDLista=" + m_IdLista.ToString() + " AND [CodUnitate]=" + ModuleInfo.CodUnitate.ToString();
            String objDt = cmd.ExecuteScalar().ToString();
            if (objDt != String.Empty)
            {
                dt = DateTime.FromOADate(Convert.ToDouble(objDt));
                if (filtruData != String.Empty)
                    filtruData += " AND ";
            }
            linia1 = "CONTUL DE EXECUTIE AL INSTITUTIILOR PUBLICE - Cheltuieli ";
            linia2 = " la data " + dt.ToString("d",cultureRO);
            if (m_IdLista == 11)
            {
                linia1 = "Executia cheltuielilor bugetare ";
                linia2 = " de la data " + dte.ToString("d",cultureRO) + " pana la "  +dt.ToString("d",cultureRO);
            }

            cmd.CommandText = "SELECT [Valoare] FROM [ParamListe] WHERE COD='DLC' AND [User]=system_user AND [Host]=host_name() AND IDLista=" + m_IdLista.ToString() + " AND [CodUnitate]=" + ModuleInfo.CodUnitate.ToString();
            String dlc = cmd.ExecuteScalar().ToString();
            cmd.CommandText = "SELECT [Valoare] FROM [ParamListe] WHERE COD='PLC' AND [User]=system_user AND [Host]=host_name() AND IDLista=" + m_IdLista.ToString() + " AND [CodUnitate]=" + ModuleInfo.CodUnitate.ToString();
            String plc = cmd.ExecuteScalar().ToString();
            String filtruCont = String.Empty;
            if (plc != String.Empty || dlc != String.Empty)
            {
                if (dlc != String.Empty)
                {
                    linia2 += " de la contul " + dlc;
                }
                if (plc != String.Empty)
                {
                    linia2 += " pana la contul " + plc;
                }
            }
            cmd.CommandText = "SELECT [IDJurnal] FROM [ParamListe] a JOIN [Jurnale] b ON b.Codificare = LTRIM(RTRIM(a.[Valoare])) " +
                    "WHERE COD='JRN' AND [User]=system_user AND [Host]=host_name() AND IDLista=" + m_IdLista.ToString() + " AND a.[CodUnitate]=" + ModuleInfo.CodUnitate.ToString();

            String sJurnal = "-1";
            if (cmd.ExecuteScalar() != null)
                sJurnal = cmd.ExecuteScalar().ToString();

            listBS.Add(new BindingSource(eSRPDS, "ExCheltCen"));
            String comanda = "[GenListaExecutieChelt]";
            
            ///sectiunea de jurnale
            if (sJurnal != "-1")
            {
                //comanda += " AND  [IdJurnal] = " + sJurnal;
                cmd.CommandText = "SELECT [Valoare] FROM [ParamListe] WHERE COD='JRN' AND [User]=system_user AND [Host]=host_name() AND IDLista=" + m_IdLista.ToString() + " AND [CodUnitate]=" + ModuleInfo.CodUnitate.ToString();
                capitol = cmd.ExecuteScalar().ToString();
            }

            listTA.Add(new SqlDataAdapter(comanda, cmd.Connection));
            listTA[1].SelectCommand.CommandType = CommandType.StoredProcedure;
            listTA[1].SelectCommand.Parameters.Add(new SqlParameter("idLista", m_IdLista.ToString()));
            listTA[1].SelectCommand.Parameters.Add(new SqlParameter("CodUnitate", ModuleInfo.CodUnitate.ToString()));
            listTA[1].SelectCommand.Parameters.Add(new SqlParameter("An", ModuleInfo.AnArhiva));
            
            listTA[1].Fill(eSRPDS.ExCheltCen);


            frm.NumeRaport = "ContExecutieInstitutii.rdlc";
            if (m_IdLista==11)
                frm.NumeRaport = "ExecutieCheltCentralizata.rdlc";

            
            //frm.dataloadHandler += new LoadDataHandler(frm_dataloadHandler);
            frm.AddDataSource("ESRPDataSet_BalconSetup", listBS[0]);
            ///filtreaza totalul...
            ///se va genera in raport
            ///
            //listBS[1].Filter = "[ArtAl]<>'0'";
            frm.AddDataSource("ESRPDataSet_ExcutieCheltuieliCentralizata", listBS[1]);
            frm.AddParameter("Linia1", linia1, true);
            frm.AddParameter("Linia2", linia2, true);
            frm.AddParameter("Capitol", capitol, true);

            cmd.CommandText = "SELECT COUNT(*) FROM [SemnaturiListe] WHERE  IDLista=" + m_IdLista + " AND [TipLista]=" + TipLista.ToString();
            Boolean eSemnaturi = Convert.ToInt32(cmd.ExecuteScalar()) != 0;
            frm.AddParameter("Semnaturi", eSemnaturi ? "True" : "False", true);

            frm.SetWindowFormat(true);
            frm.dataloadHandler += new LoadDataHandler(balanta_dataloadHandler);
            InchideConexiune(cmd.Connection);
        }

        private Boolean ListaOperatiuni(PreviewRaportFrm frm, ESRPDataSet eSRPDS)
        {
            SqlCommand cmd = new SqlCommand("", DeschideConexiune(workConnString,120));
            cmd.CommandText = "SELECT [Valoare] FROM [ParamListe] WHERE COD='DLD' AND [User]=system_user AND [Host]=host_name() AND IDLista=" + m_IdLista.ToString() + " AND [CodUnitate]=" + ModuleInfo.CodUnitate.ToString();
            String objDte = cmd.ExecuteScalar().ToString(), filtruData = String.Empty, filtruDataAnt = String.Empty;
            String linia1 = String.Empty, linia2 = String.Empty;
            DateTime dte = DateTime.Now, dt = DateTime.Now;

            if (objDte != String.Empty)
            {
                dte = DateTime.FromOADate(Convert.ToDouble(objDte));
                filtruData = " [Data] >= '" + dte.Year.ToString() + "-" + dte.Month.ToString() + "-" + dte.Day.ToString() + "'";
                filtruDataAnt = " [Data] < '" + dte.Year.ToString() + "-" + dte.Month.ToString() + "-" + dte.Day.ToString() + "'";
            }

            cmd.CommandText = "SELECT [Valoare] FROM [ParamListe] WHERE COD='PLD' AND [User]=system_user AND [Host]=host_name() AND IDLista=" + m_IdLista.ToString() + " AND [CodUnitate]=" + ModuleInfo.CodUnitate.ToString();
            String objDt = cmd.ExecuteScalar().ToString();
            if (objDt != String.Empty)
            {
                dt = DateTime.FromOADate(Convert.ToDouble(objDt));
                if (filtruData != String.Empty)
                    filtruData += " AND ";
                filtruData += " [Data] <= '" + dt.Year.ToString() + "-" + dt.Month.ToString() + "-" + dt.Day.ToString() + "'";
            }
            linia1 = "Lista operatiuni bugetare ";
            linia1 += " in intervalul " + dte.ToString("d",cultureRO) + " - " + dt.ToString("d",cultureRO);

            cmd.CommandText = "SELECT [IDJurnal] FROM [ParamListe] a JOIN [Jurnale] b ON b.Codificare = LTRIM(RTRIM(a.[Valoare])) " +
                    "WHERE COD='JRN' AND [User]=system_user AND [Host]=host_name() AND IDLista=" + m_IdLista.ToString() + " AND a.[CodUnitate]=" + ModuleInfo.CodUnitate.ToString();

            String sJurnal = "-1";
            if (cmd.ExecuteScalar() != null)
                sJurnal = cmd.ExecuteScalar().ToString();

            listBS.Add(new BindingSource(eSRPDS, "ListaOperatiuni"));          
            String comanda = "[GenListaOperatiuni]";
            
            ///sectiunea de jurnale
            if (sJurnal != "-1")
            {
                //comanda += " AND  [IdJurnal] = " + sJurnal;
                cmd.CommandText = "SELECT [Valoare] FROM [ParamListe] WHERE COD='JRN' AND [User]=system_user AND [Host]=host_name() AND IDLista=" + m_IdLista.ToString() + " AND [CodUnitate]=" + ModuleInfo.CodUnitate.ToString();
                linia2 += " pentru capitolul: " + cmd.ExecuteScalar().ToString();
            }
            cmd.CommandText = "SELECT [Valoare] FROM [ParamListe] WHERE COD='AAA' AND [User]=system_user AND [Host]=host_name() AND IDLista=" + m_IdLista.ToString() + " AND [CodUnitate]=" + ModuleInfo.CodUnitate.ToString();
            linia2 += " pentru clasificatia: " + cmd.ExecuteScalar().ToString();
            
            listTA.Add(new SqlDataAdapter(comanda, cmd.Connection));
            listTA[1].SelectCommand.CommandType = CommandType.StoredProcedure;
            listTA[1].SelectCommand.Parameters.Add(new SqlParameter("idLista", m_IdLista.ToString()));
            listTA[1].SelectCommand.Parameters.Add(new SqlParameter("CodUnitate", ModuleInfo.CodUnitate.ToString()));

            try
            {
                listTA[1].Fill(eSRPDS.ListaOperatiuni);
            }
            catch (SqlException ex)
            {
                MessageBox.Show(ex.Message);
                return false;
            }
            finally
            {
                InchideConexiune(cmd.Connection);
            }

            frm.NumeRaport = "ListaOperatiuni.rdlc";
            //frm.dataloadHandler += new LoadDataHandler(frm_dataloadHandler);
            frm.AddDataSource("ESRPDataSet_BalconSetup", listBS[0]);
            ///filtreaza totalul...
            ///se va genera in raport
            ///
            frm.AddDataSource("ESRPDataSet_ListaOperatiuni", listBS[1]);
            frm.AddParameter("Linia1", linia1, true);
            frm.AddParameter("Linia2", linia2, true);
            frm.SetWindowFormat(true);
            return true;
            
        }

        public String filtruJurnal = String.Empty;

        private void FisaCont(PreviewRaportFrm frm, ESRPDataSet eSRPDS)
        {
            TipLista = 0;
            SqlCommand cmd = new SqlCommand("", DeschideConexiune(workConnString));
            cmd.CommandText = "SELECT [Valoare] FROM [ParamListe] WHERE COD='DLD' AND [User]=system_user AND [Host]=host_name() AND IDLista=" + m_IdLista.ToString() + " AND [CodUnitate]=" + ModuleInfo.CodUnitate.ToString();            
            String obj = cmd.ExecuteScalar().ToString();
            String filtruData = String.Empty,linia1=String.Empty,linia2=String.Empty;
            DateTime dte = DateTime.Now, dt = DateTime.Now;

            if (obj != String.Empty)
                dte = DateTime.FromOADate(Convert.ToDouble(obj));
            SqlParameter[] aParam = new SqlParameter[10];
            aParam[0] = new SqlParameter("pDtDataStartUI", dte);
            cmd.CommandText = "SELECT [Valoare] FROM [ParamListe] WHERE COD='PLD' AND [User]=system_user AND [Host]=host_name() AND IDLista=" + m_IdLista.ToString() + " AND [CodUnitate]=" + ModuleInfo.CodUnitate.ToString();
            obj = cmd.ExecuteScalar().ToString();
            if (obj != String.Empty)
                dt = DateTime.FromOADate(Convert.ToDouble(obj));
            aParam[1] = new SqlParameter("pDtDataEndUI", dt);

            cmd.CommandText = "SELECT [Valoare] FROM [ParamListe] WHERE COD='ANL' AND [User]=system_user AND [Host]=host_name() AND IDLista=" + m_IdLista.ToString() + " AND [CodUnitate]=" + ModuleInfo.CodUnitate.ToString();
            String EsteAnal = cmd.ExecuteScalar().ToString();
            if (EsteAnal == "1")
            {
                linia1 = "Fisa cont analitica ";
            }
            else
                linia1 = "Fisa cont sintetica ";

            linia1 += " in intervalul " + dte.ToString("d",cultureRO) + " - " + dt.ToString("d",cultureRO);

            Int16 pCat = 0;

            cmd.CommandText = "SELECT [Valoare] FROM [ParamListe] WHERE COD='TPB' AND [User]=system_user AND [Host]=host_name() AND IDLista=" + m_IdLista + " AND [CodUnitate]=" + ModuleInfo.CodUnitate.ToString();
            String categ = cmd.ExecuteScalar().ToString();
            if (categ.ToLower() == "extra bilantiera")
                pCat = 2;
            cmd.CommandText = "SELECT [IDJurnal] FROM [ParamListe] a JOIN [Jurnale] b ON b.Codificare = LTRIM(RTRIM(a.[Valoare])) " +
                    "WHERE COD='JRN' AND [User]=system_user AND [Host]=host_name() AND IDLista=" + m_IdLista.ToString() + " AND a.[CodUnitate]=" + ModuleInfo.CodUnitate.ToString();

            String dlc = "-1";
            if (cmd.ExecuteScalar() != null)
                dlc = cmd.ExecuteScalar().ToString();

            filtruJurnal = String.Empty;
            if (dlc != "-1")
            { 
                cmd.CommandText = "SELECT [Valoare] FROM [ParamListe] WHERE COD='JRN' AND [User]=system_user AND [Host]=host_name() AND IDLista=" + m_IdLista.ToString() + " AND [CodUnitate]=" + ModuleInfo.CodUnitate.ToString();
                String jurnalSelectat = cmd.ExecuteScalar().ToString();

                linia2 += " pentru capitolul " + jurnalSelectat;
                filtruJurnal = " AND IDJurnal = " + dlc;
            }
            aParam[2] = new SqlParameter("pJurnal", Convert.ToInt16(dlc));
            aParam[3] = new SqlParameter("pCategorie", pCat);



            cmd.CommandText = "SELECT [Valoare] FROM [ParamListe] WHERE COD='DLC' AND [User]=system_user AND [Host]=host_name() AND IDLista=" + m_IdLista.ToString() + " AND [CodUnitate]=" + ModuleInfo.CodUnitate.ToString();
            dlc = cmd.ExecuteScalar().ToString();
            cmd.CommandText = "SELECT [Valoare] FROM [ParamListe] WHERE COD='PLC' AND [User]=system_user AND [Host]=host_name() AND IDLista=" + m_IdLista.ToString() + " AND [CodUnitate]=" + ModuleInfo.CodUnitate.ToString();
            String plc = cmd.ExecuteScalar().ToString();

            if (plc != String.Empty || dlc != String.Empty)
            {
                if (dlc != String.Empty)
                    linia2 = "de la contul " + dlc;
                if (plc != String.Empty)
                    linia2 += " pana la contul " + plc;
            }

            aParam[4] = new SqlParameter("pStrContStart", dlc);
            aParam[5] = new SqlParameter("pStrContEnd", plc);

            cmd.CommandText = "SELECT [Valoare] FROM [ParamListe] WHERE COD='CFM' AND [User]=system_user AND [Host]=host_name() AND IDLista=" + m_IdLista.ToString() + " AND [CodUnitate]=" + ModuleInfo.CodUnitate.ToString();
            String cfm = cmd.ExecuteScalar().ToString();

            aParam[6] = new SqlParameter("pCfm", Convert.ToInt16(cfm));
            aParam[7] = new SqlParameter("pAnalitica", Convert.ToInt16(EsteAnal.ToString()));
            aParam[8] = new SqlParameter("pCfmRulaje", Convert.ToInt16(cfm));


            listBS.Add(new BindingSource(eSRPDS, "BalantaView"));


            listTA.Add(new SqlDataAdapter("balcon_GetBalanta", cmd.Connection));
            ((SqlDataAdapter)listTA[1]).SelectCommand.CommandType = CommandType.StoredProcedure;
            aParam[9] = new SqlParameter("pTerminal", Convert.ToInt16(0));
            if (EsteAnal == "1")
            {
                aParam[9] = new SqlParameter("pTerminal", Convert.ToInt16(1));
            }
            if (ModuleInfo.AnArhiva != String.Empty)
            {
                listTA[1].SelectCommand.CommandText = "balcon_GetBalantaArh";
                SqlParameter[] aParam2 = new SqlParameter[11];
                aParam.CopyTo(aParam2, 0);
                aParam2[10] = new SqlParameter("pAn", Convert.ToInt16(ModuleInfo.AnArhiva));
                ((SqlDataAdapter)listTA[1]).SelectCommand.Parameters.AddRange(aParam2);
            }
            else
                ((SqlDataAdapter)listTA[1]).SelectCommand.Parameters.AddRange(aParam);




            ((SqlDataAdapter)listTA[1]).SelectCommand.CommandTimeout = 120;
           
          
            listTA[1].Fill(eSRPDS.BalantaView);
            //listTA[2].Fill(eSRPDS.NotaContabilaView);


            frm.NumeRaport = "FisaCont.rdlc";
            if(!bDocumentJustifRulaj)
                frm.NumeRaport = "FisaContCompact.rdlc";

            frm.dataloadHandler += new LoadDataHandler(FisaCont_dataloadHandler);
            listBS[1].Sort = "SortValue";
            frm.AddDataSource("ESRPDataSet_BalantaView", listBS[1]);
            frm.AddDataSource("ESRPDataSet_BalconSetup", ((BindingSource)listBS[0]));
            //listBS[2].Filter = "ContDebit='@Val0' OR ContCredit = '@Val0'";
            //frm.AddSubreportDataSource("ESRPDataSet_NotaContabilaView", listBS[2]);
            frm.AddParameter("DeLaData",dte.ToOADate().ToString(),true);
            frm.AddParameter("PanaLaData",dt.ToOADate().ToString(), true);
            frm.AddParameter("Linia1", linia1, true);
            frm.AddParameter("Linia2", linia2, true);
            frm.AddParameter("Analitica", EsteAnal == "1" ? "True" : "False", true);
            frm.AddParameter("DocJust", bDocumentJustifRulaj ? "True" : "False", true);

            cmd.CommandText = "SELECT COUNT(*) FROM [SemnaturiListe] WHERE  IDLista=" + m_IdLista + " AND [TipLista]=" + TipLista.ToString();
            Boolean eSemnaturi = Convert.ToInt32(cmd.ExecuteScalar()) != 0;
            frm.AddParameter("Semnaturi", eSemnaturi ? "True" : "False", true);

            frm.SetWindowFormat(true);
            InchideConexiune(cmd.Connection);
        }

        private void Balanta(PreviewRaportFrm frm, ESRPDataSet eSRPDS)
        {
            MyTrace("0-->>Balanta");
            TipLista = 0;
            SqlCommand cmd = new SqlCommand("", DeschideConexiune(workConnString,120));
            cmd.CommandText = "SELECT [Valoare] FROM [ParamListe] WHERE COD='LDT' AND [User]=system_user AND [Host]=host_name() AND IDLista=" + m_IdLista + " AND [CodUnitate]=" + ModuleInfo.CodUnitate.ToString();
            String obj = cmd.ExecuteScalar().ToString();

            DateTime dt = DateTime.Now;
            String linia1 = String.Empty, linia2 = String.Empty, filtruTotal=String.Empty;

            if (obj != String.Empty)
                dt = DateTime.FromOADate(Convert.ToDouble(obj));

            MyTrace("0----Read LDT value");
            cmd.CommandText = "SELECT [Valoare] FROM [ParamListe] WHERE COD='ANL' AND [User]=system_user AND [Host]=host_name() AND IDLista=" + m_IdLista + " AND [CodUnitate]=" + ModuleInfo.CodUnitate.ToString();
            String EsteAnal = cmd.ExecuteScalar().ToString();
            if (EsteAnal == "1")
            {
                linia1 = "Balanta analitica ";
                //filtruTotal = " AND [EsteAnalitic]= 1";
                TipLista = 1;
            }
            else
            {
                linia1 = "Balanta sintetica ";
                //filtruTotal = " AND [EsteAnalitic]= 0";
            }
            MyTrace("0----Read ANL value");
            linia1 += " la data " + dt.ToString("d", cultureRO);

            cmd.CommandText = "SELECT [Valoare] FROM [ParamListe] WHERE COD='TPB' AND [User]=system_user AND [Host]=host_name() AND IDLista=" + m_IdLista + " AND [CodUnitate]=" + ModuleInfo.CodUnitate.ToString();
            String TipBalanta = cmd.ExecuteScalar().ToString();
            MyTrace("0----Read TPB value");
            if (TipBalanta == "Financiara")
            {
                
                filtruTotal += " AND [Categorie]= 0";
            }
            else
            {

                filtruTotal += " AND [Categorie]= 2";
            }


            cmd.CommandText = "SELECT [Valoare] FROM [ParamListe] WHERE COD='DLC' AND [User]=system_user AND [Host]=host_name() AND IDLista=" + m_IdLista + " AND [CodUnitate]=" + ModuleInfo.CodUnitate.ToString();
            String dlc = cmd.ExecuteScalar().ToString();
            MyTrace("0----Read DLC value");
            cmd.CommandText = "SELECT [Valoare] FROM [ParamListe] WHERE COD='PLC' AND [User]=system_user AND [Host]=host_name() AND IDLista=" + m_IdLista + " AND [CodUnitate]=" + ModuleInfo.CodUnitate.ToString();
            String plc = cmd.ExecuteScalar().ToString();
            MyTrace("0----Read PLC value");
            if (plc != String.Empty || dlc != String.Empty)
            {
                if (dlc != String.Empty)
                {
                    linia2 = "de la contul " + dlc;
                    filtruTotal += " AND Cont>='" + dlc + "'";
                }
                if (plc != String.Empty)
                {
                    linia2 += " pana la contul " + plc;
                    filtruTotal += " AND Cont<='" + plc + "'";
                }
            }

            cmd.CommandText = "SELECT [IDJurnal] FROM [ParamListe] a JOIN [Jurnale] b ON b.Codificare = LTRIM(RTRIM(a.[Valoare])) " +
                    "WHERE COD='JRN' AND [User]=system_user AND [Host]=host_name() AND IDLista=" + m_IdLista.ToString() + " AND a.[CodUnitate]=" + ModuleInfo.CodUnitate.ToString();
            Int16 idJurnal = -1;
            if (cmd.ExecuteScalar() != null)
            {
                idJurnal = Convert.ToInt16(cmd.ExecuteScalar().ToString());
                //filtruTotal += " AND [IDJurnal]=" + idJurnal.ToString();
                cmd.CommandText = "SELECT [Valoare] FROM [ParamListe] WHERE COD='JRN' AND [User]=system_user AND [Host]=host_name() AND IDLista=" + m_IdLista + " AND [CodUnitate]=" + ModuleInfo.CodUnitate.ToString();
                String jurnalSelectat = cmd.ExecuteScalar().ToString();
                linia2 += " pentru capitolul " + jurnalSelectat;

            }
            MyTrace("0----Read JRN value");
            cmd.CommandText = "SELECT [Valoare] FROM [ParamListe] WHERE COD='STL' AND [User]=system_user AND [Host]=host_name() AND IDLista=" + m_IdLista + " AND [CodUnitate]=" + ModuleInfo.CodUnitate.ToString();
            String stl = cmd.ExecuteScalar().ToString();
            cmd.CommandText = "SELECT [Valoare] FROM [ParamListe] WHERE COD='CMP' AND [User]=system_user AND [Host]=host_name() AND IDLista=" + m_IdLista + " AND [CodUnitate]=" + ModuleInfo.CodUnitate.ToString();
            String cmp = cmd.ExecuteScalar().ToString();
            cmd.CommandText = "SELECT [Valoare] FROM [ParamListe] WHERE COD='TGC' AND [User]=system_user AND [Host]=host_name() AND IDLista=" + m_IdLista + " AND [CodUnitate]=" + ModuleInfo.CodUnitate.ToString();
            String tcg = cmd.ExecuteScalar().ToString();


            listBS.Add(new BindingSource(eSRPDS, "BalantaView"));
            listTA.Add(new SqlDataAdapter("[balcon_GenListaBalanta]", cmd.Connection));
            

            listTA[1].SelectCommand.CommandType = CommandType.StoredProcedure;
            listTA[1].SelectCommand.Parameters.Add(new SqlParameter("An", ModuleInfo.AnArhiva));
            listTA[1].SelectCommand.CommandTimeout = 120;
            MyTrace("0----Before Fill BalantaView");
            MyTrace("0----" + listTA[1].SelectCommand.CommandText);
            foreach(SqlParameter par in listTA[1].SelectCommand.Parameters)
                MyTrace("0----" + par.ParameterName + "=" + par.Value.ToString());
          
            listTA[1].Fill(eSRPDS.BalantaView);
            MyTrace("0----Fill BalantaView");
            //listBS[1].Sort = "SortValue";

            listBS.Add(new BindingSource(eSRPDS, "Semnaturi"));
            listTA.Add(new SqlDataAdapter("SELECT * FROM [Semnaturi]", cmd.Connection));
            listTA[listTA.Count-1].Fill(eSRPDS.Semnaturi);
            MyTrace("0----Fill Semnaturi");

            frm.NumeRaport = "Balanta.rdlc";
            if (cmp == "1")
                frm.NumeRaport = "BalantaCompact.rdlc";
            if (stl == "ITCSF")
            {
                frm.NumeRaport = "BalantaICLTS.rdlc";
                if (cmp == "1")
                    frm.NumeRaport = "BalantaICLTSCompact.rdlc";
            }
            else
                if (stl == "ITSCF")
                {
                    frm.NumeRaport = "BalantaICTLS.rdlc";
                    if (cmp == "1")
                        frm.NumeRaport = "BalantaICTLSCompact.rdlc";           
                }
            if(tcg=="1")
                frm.NumeRaport = "BalantaTCG.rdlc";

            frm.AddDataSource("ESRPDataSet_BalantaView", listBS[1]);
            frm.AddDataSource("ESRPDataSet_BalconSetup", listBS[0]);
            //frm.AddDataSource("ESRPDataSet_Semnaturi", listBS[2]);
            MyTrace("0----add data source");

            frm.AddParameter("Linia1", linia1, true);
            frm.AddParameter("Linia2", linia2, true);

            if (frm.NumeRaport == "BalantaICLTS.rdlc" || frm.NumeRaport == "BalantaICTLS.rdlc")
            {
                cmd.CommandText = "SELECT COUNT(*) FROM [SemnaturiListe] WHERE  IDLista=" + m_IdLista + " AND [TipLista]=" + TipLista.ToString();
                Boolean eSemnaturi = Convert.ToInt32(cmd.ExecuteScalar()) != 0;
                frm.AddParameter("Semnaturi", eSemnaturi ? "True" : "False", true);
            }

          
            frm.SetWindowFormat(true);
            frm.dataloadHandler += new LoadDataHandler(balanta_dataloadHandler);
            InchideConexiune(cmd.Connection);
            MyTrace("<<--oBalanta");
        }

        private Boolean RegistruJurnal(PreviewRaportFrm frm, ESRPDataSet eSRPDS)
        {
            SqlCommand cmd = new SqlCommand("", DeschideConexiune(workConnString));
            cmd.CommandText = "SELECT [Valoare] FROM [ParamListe] WHERE COD='DLD' AND [User]=system_user AND [Host]=host_name() AND IDLista=" + m_IdLista.ToString() + " AND [CodUnitate]="+ModuleInfo.CodUnitate.ToString();
                        
            String filtruData = String.Empty;
            String filtruCat = String.Empty;
            String linia1 = String.Empty, linia2 = String.Empty;
            DateTime dt = DateTime.MaxValue, dte = DateTime.MinValue;


            String objDte = cmd.ExecuteScalar().ToString();
            if (objDte != String.Empty)
            {
                dte = DateTime.FromOADate(Convert.ToDouble(objDte));
                filtruData = " DataDoc >= @DataStart ";
            }


            cmd.CommandText = "SELECT [Valoare] FROM [ParamListe] WHERE COD='PLD' AND [User]=system_user AND [Host]=host_name() AND IDLista=" + m_IdLista.ToString() + " AND [CodUnitate]=" + ModuleInfo.CodUnitate.ToString();
            String objDt = cmd.ExecuteScalar().ToString();
            if (objDt != String.Empty)
            {
                dt = DateTime.FromOADate(Convert.ToDouble(objDt));
                if (filtruData != String.Empty)
                    filtruData += "AND ";
                filtruData += " DataDoc <= @DataEnd ";
            }


            cmd.CommandText = "SELECT [Valoare] FROM [ParamListe] WHERE COD='RGJ' AND [User]=system_user AND [Host]=host_name() AND IDLista=" + m_IdLista.ToString() + " AND [CodUnitate]=" + ModuleInfo.CodUnitate.ToString();
            String tipJurn = cmd.ExecuteScalar().ToString();

            if (tipJurn == "In afara bilantului")
                filtruCat = "[Categorie] = 2";
            else
                filtruCat = "[Categorie] = 0";

            cmd.CommandText = "SELECT [Valoare] FROM [ParamListe] WHERE COD='DTL' AND [User]=system_user AND [Host]=host_name() AND IDLista=" + m_IdLista.ToString() + " AND [CodUnitate]=" + ModuleInfo.CodUnitate.ToString();
            String centralizat = cmd.ExecuteScalar().ToString();
            if (centralizat == "Centralizat")
                centralizat = "True";
            else
                centralizat = "False";

            linia1 = "Registru Jurnal " + tipJurn;
            linia1 += " in intervalul " + dte.ToString("d",cultureRO) + " - " + dt.ToString("d",cultureRO);

            cmd.CommandText = "SELECT [Valoare] FROM [ParamListe] WHERE COD='CTD' AND [User]=system_user AND [Host]=host_name() AND IDLista=" + m_IdLista.ToString() + " AND [CodUnitate]=" + ModuleInfo.CodUnitate.ToString();
            Object odlc = cmd.ExecuteScalar();
            String dlc = String.Empty;
            if (odlc != null) dlc = odlc.ToString();

            cmd.CommandText = "SELECT [Valoare] FROM [ParamListe] WHERE COD='CTC' AND [User]=system_user AND [Host]=host_name() AND IDLista=" + m_IdLista.ToString() + " AND [CodUnitate]=" + ModuleInfo.CodUnitate.ToString();
            Object oplc = cmd.ExecuteScalar();
            String plc = String.Empty;
            if (oplc != null)
                plc = oplc.ToString();

            if (plc != String.Empty && dlc != String.Empty)
            {
                MessageBox.Show("Lista nu poate fi generata pentru un cont debit si un cont credit simultan!");
                return false ;
            }
            String filtruContDebit = String.Empty;
            String filtruContCredit = String.Empty;
            String filtruCont = String.Empty;
            if (plc != String.Empty || dlc != String.Empty)
            {

                if (dlc != String.Empty)
                {
                    linia2 = "pentru contul " + dlc;
                    filtruContDebit += "ContDebit Like '" + dlc + "%'";
                    filtruCont = " AND " + filtruContDebit;
                }
                if (plc != String.Empty)
                {
                    linia2 += " pentru contul " + plc;
                    filtruContCredit += "ContCredit LIKE '" + plc + "%'";
                    filtruCont = " AND " + filtruContCredit;
                }
                
            }
            cmd.CommandText = "SELECT [IDJurnal] FROM [ParamListe] a JOIN [Jurnale] b ON b.Codificare = LTRIM(RTRIM(a.[Valoare])) " +
                    "WHERE COD='JRN' AND [User]=system_user AND [Host]=host_name() AND IDLista=" + m_IdLista.ToString() + " AND a.[CodUnitate]=" + ModuleInfo.CodUnitate.ToString();

            String sJurnal = "-1";
            if (cmd.ExecuteScalar() != null)
                sJurnal = cmd.ExecuteScalar().ToString();


            listBS.Add(new BindingSource(eSRPDS, "NotaContabilaView"));
            String comanda = "AND ContDebit<>'N/A' AND ContCredit<>'N/A' ";
            String filtreTot = String.Empty ;
            ///sectiunea de jurnale
            if (filtruCat != String.Empty)
            {
                filtreTot += " AND " + filtruCat;
            }
            
            //comanda += " ORDER BY " + (Debit == "Debit" ? "ContDebit" : "ContCredit");
            //listTA.Add(new SqlDataAdapter("SELECT * FROM BalantaView", cmd.Connection));

            SumDocFormula sdf = new SumDocFormula(cmd.Connection);
            if (dlc == String.Empty && plc == String.Empty)
                sdf.CalcSume(filtreTot, filtruContDebit, filtruContCredit, dte, dt, sJurnal, false, ModuleInfo);
            else
                sdf.CalcSume(filtreTot, filtruContDebit, filtruContCredit, dte, dt, sJurnal, true, ModuleInfo);

            if (sJurnal != "-1")
            {
                filtreTot += " AND [IdJurnal] = " + sJurnal;
                cmd.CommandText = "SELECT [Valoare] FROM [ParamListe] WHERE COD='JRN' AND [User]=system_user AND [Host]=host_name() AND IDLista=" + m_IdLista.ToString() + " AND [CodUnitate]=" + ModuleInfo.CodUnitate.ToString();
                linia2 += " pentru " + cmd.ExecuteScalar().ToString();
            }

            if (filtruCont != String.Empty)
            {
                filtreTot += filtruCont;
            }
            comanda += filtreTot;
            

            listTA.Add(new SqlDataAdapter("[GenNotaContabila]", cmd.Connection));
            listTA[listTA.Count - 1].SelectCommand.CommandType = CommandType.StoredProcedure;
            listTA[listTA.Count - 1].SelectCommand.Parameters.Add(new SqlParameter("@cont", String.Empty));
            listTA[listTA.Count - 1].SelectCommand.Parameters.Add(new SqlParameter("@CodUnitate", Convert.ToInt16(ModuleInfo.CodUnitate)));
            listTA[listTA.Count - 1].SelectCommand.Parameters.Add(new SqlParameter("@DeLaData", dte));
            listTA[listTA.Count - 1].SelectCommand.Parameters.Add(new SqlParameter("@PanaLaData", dt));
            if (ModuleInfo.AnArhiva == String.Empty)
                listTA[listTA.Count - 1].SelectCommand.Parameters.Add(new SqlParameter("@An", Convert.ToInt16(0)));
            else
                listTA[listTA.Count - 1].SelectCommand.Parameters.Add(new SqlParameter("@An", Convert.ToInt16(ModuleInfo.AnArhiva)));
            listTA[listTA.Count - 1].SelectCommand.Parameters.Add(new SqlParameter("@strFilter", comanda));
            listTA[listTA.Count - 1].SelectCommand.Parameters.Add(new SqlParameter("@strOrder", String.Empty));

            listTA[1].Fill(eSRPDS.NotaContabilaView);

            cmd.CommandText = "SELECT [Valoare] FROM [ParamListe] WHERE COD='CMP' AND [User]=system_user AND [Host]=host_name() AND IDLista=" + m_IdLista + " AND [CodUnitate]=" + ModuleInfo.CodUnitate.ToString();
            String cmp = cmd.ExecuteScalar().ToString();

            frm.NumeRaport = "RegistruJurnal.rdlc";
            if(cmp=="1")
                frm.NumeRaport = "RegistruJurnalCompact.rdlc";
            else
                if (!bDocumentJustifRulaj)
                    frm.NumeRaport = "RegistruJurnalFaraJustificative.rdlc";

            frm.dataloadHandler += new LoadDataHandler(frm_dataloadHandler);
            frm.AddDataSource("ESRPDataSet_BalconSetup", listBS[0]);
            frm.AddDataSource("ESRPDataSet_NotaContabilaView", listBS[1]);
            frm.AddParameter("Linia1", linia1, true);
            frm.AddParameter("Linia2", linia2, true);
            
            frm.AddParameter("DebitInitial", sdf.debInit, true);
            frm.AddParameter("CreditInitial", sdf.creInit, true);
            frm.AddParameter("DebitPrecedent", sdf.debPrec, true);
            frm.AddParameter("CreditPrecedent", sdf.crePrec, true);
            frm.AddParameter("RulajDebit", sdf.rulajDeb, true);
            frm.AddParameter("RulajCredit", sdf.rulajCre, true);
            frm.AddParameter("TotalSumeDebit", sdf.totalDeb, true);
            frm.AddParameter("TotalSumeCredit", sdf.totalCre, true);
            frm.AddParameter("Centralizat", centralizat, true);

            //frm.AddParameter("Debit", Debit == "Debit" ? "True" : "False", true);
            frm.SetWindowFormat(false);
            InchideConexiune(cmd.Connection);
            return true;
        }

        private Boolean CarteaMare(PreviewRaportFrm frm, ESRPDataSet eSRPDS)
        {

            SqlCommand cmd = new SqlCommand("", DeschideConexiune(workConnString));
            DateTime dt = DateTime.MaxValue,dte=DateTime.MinValue;
            String linia1 = String.Empty, linia2 = String.Empty, filtruTotal = String.Empty;


            cmd.CommandText = "SELECT [Valoare] FROM [ParamListe] WHERE COD='DLD' AND [User]=system_user AND [Host]=host_name() AND IDLista=" + m_IdLista.ToString() + " AND [CodUnitate]=" + ModuleInfo.CodUnitate.ToString();
            String objDte = cmd.ExecuteScalar().ToString(), filtruData = String.Empty;
            if (objDte != String.Empty)
            {
                dte = DateTime.FromOADate(Convert.ToDouble(objDte));
                filtruData = " DataDoc >= @DataStart ";
            }


            cmd.CommandText = "SELECT [Valoare] FROM [ParamListe] WHERE COD='PLD' AND [User]=system_user AND [Host]=host_name() AND IDLista=" + m_IdLista.ToString() + " AND [CodUnitate]=" + ModuleInfo.CodUnitate.ToString();
            String objDt = cmd.ExecuteScalar().ToString();
            if (objDt != String.Empty)
            {
                dt = DateTime.FromOADate(Convert.ToDouble(objDt));
                if (filtruData != String.Empty)
                    filtruData += "AND ";
                filtruData += " DataDoc <= @DataEnd ";
            }


            cmd.CommandText = "SELECT [Valoare] FROM [ParamListe] WHERE COD='OCT' AND [User]=system_user AND [Host]=host_name() AND IDLista=" + m_IdLista.ToString() + " AND [CodUnitate]=" + ModuleInfo.CodUnitate.ToString();
            String Debit = cmd.ExecuteScalar().ToString();
            if (Debit == "Debit")
                linia1 = "Cartea Mare(SAH) debit ";
            else
                linia1 = "Cartea Mare(SAH) credit ";

            linia1 += " in intervalul " + dte.ToString("d",cultureRO) + " - " + dt.ToString("d",cultureRO);

            cmd.CommandText = "SELECT [Valoare] FROM [ParamListe] WHERE COD='DLC' AND [User]=system_user AND [Host]=host_name() AND IDLista=" + m_IdLista.ToString() + " AND [CodUnitate]=" + ModuleInfo.CodUnitate.ToString();
            String dlc = cmd.ExecuteScalar().ToString();
            cmd.CommandText = "SELECT [Valoare] FROM [ParamListe] WHERE COD='PLC' AND [User]=system_user AND [Host]=host_name() AND IDLista=" + m_IdLista.ToString() + " AND [CodUnitate]=" + ModuleInfo.CodUnitate.ToString();
            String plc = cmd.ExecuteScalar().ToString();
            String filtruCont = String.Empty;
            if (plc != String.Empty || dlc != String.Empty)
            {
                if (dlc != String.Empty)
                {
                    linia2 = "de la contul " + dlc;
                    filtruCont += "#Cont# >= '" + dlc + "'";
                }
                if (plc != String.Empty)
                {
                    linia2 += " pana la contul " + plc;
                    if (filtruCont != String.Empty)
                        filtruCont += " AND ";
                    filtruCont += "#Cont# <= '" + plc + "'";
                }
                filtruCont = " AND " + filtruCont;
            }
            cmd.CommandText = "SELECT [IDJurnal] FROM [ParamListe] a JOIN [Jurnale] b ON b.Codificare = LTRIM(RTRIM(a.[Valoare])) " +
                    "WHERE COD='JRN' AND [User]=system_user AND [Host]=host_name() AND IDLista=" + m_IdLista.ToString() + " AND a.[CodUnitate]=" + ModuleInfo.CodUnitate.ToString();

            String sJurnal = "-1";
            if (cmd.ExecuteScalar() != null)
                sJurnal = cmd.ExecuteScalar().ToString();

            listBS.Add(new BindingSource(eSRPDS, "NotaContabilaView"));
            String comanda = " AND ContDebit<>'N/A' AND ContCredit<>'N/A' ";
            /*if (filtruData != String.Empty)
            {
                comanda += " AND " + filtruData;
            }
             */
            if (filtruCont != String.Empty)
            {
                if (Debit == "Debit")
                    filtruCont = filtruCont.Replace("#Cont#", "ContDebit");
                else
                    filtruCont = filtruCont.Replace("#Cont#", "ContCredit");
                comanda += filtruCont;
            }
            ///sectiunea de jurnale
            /*if (filtruData != String.Empty && (sJurnal != "-1"))
            {
                comanda += " AND ";
            }*/
            if (sJurnal != "-1")
            {
                comanda += " AND [IdJurnal] = " + sJurnal;
                cmd.CommandText = "SELECT [Valoare] FROM [ParamListe] WHERE COD='JRN' AND [User]=system_user AND [Host]=host_name() AND IDLista=" + m_IdLista.ToString() + " AND [CodUnitate]=" + ModuleInfo.CodUnitate.ToString();
                linia2 += " pentru " + cmd.ExecuteScalar().ToString();
            }



            //listTA.Add(new SqlDataAdapter("[balcon_GenNotaContabila]", cmd.Connection));
            //listTA[listTA.Count - 1].SelectCommand.CommandType = CommandType.StoredProcedure;
            //listTA[listTA.Count - 1].SelectCommand.Parameters.Add(new SqlParameter("@cont", String.Empty));
            //listTA[listTA.Count - 1].SelectCommand.Parameters.Add(new SqlParameter("@CodUnitate", Convert.ToInt16(ModuleInfo.CodUnitate)));
            //listTA[listTA.Count - 1].SelectCommand.Parameters.Add(new SqlParameter("@DeLaData", dte));
            //listTA[listTA.Count - 1].SelectCommand.Parameters.Add(new SqlParameter("@PanaLaData", dt));
            //if (ModuleInfo.AnArhiva == String.Empty)
            //    listTA[listTA.Count - 1].SelectCommand.Parameters.Add(new SqlParameter("@An", Convert.ToInt16(0)));
            //else
            //    listTA[listTA.Count - 1].SelectCommand.Parameters.Add(new SqlParameter("@An", Convert.ToInt16(ModuleInfo.AnArhiva)));
            //listTA[listTA.Count - 1].SelectCommand.Parameters.Add(new SqlParameter("@iOrder", (Debit == "Debit" ? Convert.ToInt16(1) : Convert.ToInt16(2))));
            //listTA[1].Fill(eSRPDS.NotaContabilaView);

            this.balcon_GenNotaContabilaTableAdapter.Connection = cmd.Connection;
            this.balcon_GenNotaContabilaTableAdapter.Fill(this.eSRPDataSetListe.balcon_GenNotaContabila,
                m_IdLista,
                String.Empty, 
                Convert.ToInt16(ModuleInfo.CodUnitate),
                dte, 
                dt,
                (ModuleInfo.AnArhiva == String.Empty ? (Int16)0 : Convert.ToInt16(ModuleInfo.AnArhiva)),
                (Debit == "Debit" ? Convert.ToInt16(1) : Convert.ToInt16(2)),
                String.Empty,
                String.Empty);


            frm.NumeRaport = "CarteaMare.rdlc";
            frm.dataloadHandler += new LoadDataHandler(frm_dataloadHandlerCarteaMare);
            frm.AddDataSource("ESRPDataSet_BalconSetup", listBS[0]);
            frm.AddDataSource("ESRPDataSet_NotaContabilaView", balcon_GenNotaContabilaBindingSource);
            frm.AddParameter("Linia1", linia1, true);
            frm.AddParameter("Linia2", linia2, true);
            frm.AddParameter("Debit", Debit == "Debit" ? "True" : "False", true);
            frm.AddParameter("DeLaData", dte.ToOADate().ToString(), true);
            frm.AddParameter("PanaLaData", dt.ToOADate().ToString(), true);
            frm.SetWindowFormat(true);
            return true;
        }

        private String FiltruRCDebit = String.Empty;
        private String FiltruRCCredit = String.Empty;

        private Boolean RegistruCasa(PreviewRaportFrm frm, ESRPDataSet eSRPDS,String Titlu)
        {
            SqlCommand cmd = new SqlCommand("", DeschideConexiune(workConnString));
            cmd.CommandText = "SELECT [Valoare] FROM [ParamListe] WHERE COD='DLD' AND [User]=system_user AND [Host]=host_name() AND IDLista=" + m_IdLista.ToString() + " AND [CodUnitate]=" + ModuleInfo.CodUnitate.ToString();
            String objDte = cmd.ExecuteScalar().ToString();
            String filtruData = String.Empty;

            DateTime dte=DateTime.MinValue, dt=DateTime.MaxValue;
            if (objDte != String.Empty)
            {
                dte = DateTime.FromOADate(Convert.ToDouble(objDte));
                filtruData = " DataDoc >= @DataStart ";
            }


            cmd.CommandText = "SELECT [Valoare] FROM [ParamListe] WHERE COD='PLD' AND [User]=system_user AND [Host]=host_name() AND IDLista=" + m_IdLista.ToString() + " AND [CodUnitate]=" + ModuleInfo.CodUnitate.ToString();
            String objDt = cmd.ExecuteScalar().ToString();
            if (objDt != String.Empty)
            {
                dt = DateTime.FromOADate(Convert.ToDouble(objDt));
                if (filtruData != String.Empty)
                    filtruData += "AND ";
                filtruData += " DataDoc <= @DataEnd ";
            }

            cmd.CommandText = "SELECT [Valoare] FROM [ParamListe] WHERE COD='TPD' AND [User]=system_user AND [Host]=host_name() AND IDLista=" + m_IdLista.ToString() + " AND [CodUnitate]=" + ModuleInfo.CodUnitate.ToString();
            Object tpd = cmd.ExecuteScalar();
            Boolean bDataInTitlu = false;
            if (tpd != null && tpd.ToString() == "1")
                bDataInTitlu = true;


            String linia1 = Titlu + " ",linia2=String.Empty; //+ tipJurn;
            if (!bDataInTitlu)
                linia2 += " in intervalul " + dte.ToString("d",cultureRO) + " - " + dt.ToString("d",cultureRO);

            cmd.CommandText = "SELECT [Cont] FROM [ConturiSpeciale] WHERE [CodUnitate]=" + ModuleInfo.CodUnitate.ToString() + " AND [Tipuri] like '%CCS%'";
            SqlDataReader dr = cmd.ExecuteReader();
            if (dr == null || !dr.HasRows)
            {
                MessageBox.Show("Nu s-a definit nici un cont de casa", "Eroare", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                return false;
            }
            String filtruCont = String.Empty;
            while (dr.Read())
            {
                if (filtruCont != String.Empty)
                    filtruCont += ",";
                filtruCont += "'" + dr["Cont"].ToString() + "'";
            }
            dr.Close();
            
            String filtreTot = String.Empty, filtreTotSuma = String.Empty, filtreTotCredit = String.Empty;
            
            
            String filtruContCredit = String.Empty;
            filtruContCredit = " AND CONTCREDIT IN  (" + filtruCont + ")";
            String filtruSume = " AND CONT IN  (" + filtruCont + ")";
            filtruCont = " AND CONTDEBIT IN  (" + filtruCont + ")";

            cmd.CommandText = "SELECT [IDJurnal] FROM [ParamListe] a JOIN [Jurnale] b ON b.Codificare = LTRIM(RTRIM(a.[Valoare])) " +
                    "WHERE COD='JRN' AND [User]=system_user AND [Host]=host_name() AND IDLista=" + m_IdLista.ToString() + " AND a.[CodUnitate]=" + ModuleInfo.CodUnitate.ToString();

            String sJurnal = "-1";
            if (cmd.ExecuteScalar() != null)
                sJurnal = cmd.ExecuteScalar().ToString();

            listBS.Add(new BindingSource(eSRPDS, "balcon_GenRegistruCasa"));

            //String comanda = "SELECT ContDebit,ContCredit,'D' AS Tip,NumarDoc,DataDoc,NumarNota,ValoareLei,IdJurnal,TipDocJust,NumarDocJust,DataDocJust,ExplicatiiDocJust,TipFormula,Categorie FROM NotaContabilaView WHERE [ContDebit]<>'N/A' " + " AND [CodUnitate]=" + ModuleInfo.CodUnitate.ToString();
            //String Comanda2 = "SELECT ContCredit AS ContDebit,ContDebit AS ContCredit,'C' AS Tip,NumarDoc,DataDoc,NumarNota,ValoareLei,IdJurnal,TipDocJust,NumarDocJust,DataDocJust,ExplicatiiDocJust,TipFormula,Categorie FROM NotaContabilaView WHERE [ContCredit]<>'N/A' " + " AND [CodUnitate]=" + ModuleInfo.CodUnitate.ToString();
        
            ///sectiunea de jurnale
            if (filtruCont != String.Empty)
            {
                filtreTot += filtruCont;
                filtreTotCredit += filtruContCredit;
            }

            SumDocFormula sdf = new SumDocFormula(cmd.Connection);
            sdf.CalcTotal(filtruSume, dte, dt, Convert.ToInt16(sJurnal), ModuleInfo);

            if (sJurnal != "-1")
            {
                filtreTot += " AND [IdJurnal] = " + sJurnal;
                filtreTotCredit += " AND [IdJurnal] = " + sJurnal;
                cmd.CommandText = "SELECT [Valoare] FROM [ParamListe] WHERE COD='JRN' AND [User]=system_user AND [Host]=host_name() AND IDLista=" + m_IdLista.ToString() + " AND [CodUnitate]=" + ModuleInfo.CodUnitate.ToString();
                linia2 += " pentru " + cmd.ExecuteScalar().ToString();
            }

            listTA.Add(new SqlDataAdapter("[balcon_GenRegistruCasa]", cmd.Connection));
            listTA[listTA.Count - 1].SelectCommand.CommandType = CommandType.StoredProcedure;
            listTA[listTA.Count - 1].SelectCommand.Parameters.Add(new SqlParameter("@CodUnitate", Convert.ToInt16(ModuleInfo.CodUnitate)));
            listTA[listTA.Count - 1].SelectCommand.Parameters.Add(new SqlParameter("@DeLaData", dte));
            listTA[listTA.Count - 1].SelectCommand.Parameters.Add(new SqlParameter("@PanaLaData", dt));
            listTA[listTA.Count - 1].SelectCommand.Parameters.Add(new SqlParameter("@Cod", "%{CCS}%"));
            listTA[listTA.Count - 1].SelectCommand.Parameters.Add(new SqlParameter("@DeLaCont", ""));
            listTA[listTA.Count - 1].SelectCommand.Parameters.Add(new SqlParameter("@PanaLaCont", ""));
            FiltruRCCredit = filtreTotCredit;
            FiltruRCDebit = filtreTot;
            /*listTA[listTA.Count - 1].SelectCommand.Parameters.Add(new SqlParameter("@cont", String.Empty));
            listTA[listTA.Count - 1].SelectCommand.Parameters.Add(new SqlParameter("@CodUnitate", Convert.ToInt16(ModuleInfo.CodUnitate)));
            listTA[listTA.Count - 1].SelectCommand.Parameters.Add(new SqlParameter("@DeLaData", dte));
            listTA[listTA.Count - 1].SelectCommand.Parameters.Add(new SqlParameter("@PanaLaData", dt));
            if (dscModule.AnArhiva == String.Empty)
                listTA[listTA.Count - 1].SelectCommand.Parameters.Add(new SqlParameter("@An", Convert.ToInt16(0)));
            else
                listTA[listTA.Count - 1].SelectCommand.Parameters.Add(new SqlParameter("@An", Convert.ToInt16(dscModule.AnArhiva)));
            listTA[listTA.Count - 1].SelectCommand.Parameters.Add(new SqlParameter("@strFilter", filtreTot));
            listTA[listTA.Count - 1].SelectCommand.Parameters.Add(new SqlParameter("@strFilter2", filtreTotCredit));
            listTA[listTA.Count - 1].SelectCommand.Parameters.Add(new SqlParameter("@strOrder", String.Empty));
             */
            listTA[1].Fill(eSRPDS.balcon_GenRegistruCasa);

            cmd.CommandText = "SELECT [Valoare] FROM [ParamListe] WHERE COD='CMP' AND [User]=system_user AND [Host]=host_name() AND IDLista=" + m_IdLista + " AND [CodUnitate]=" + ModuleInfo.CodUnitate.ToString();
            String cmp = cmd.ExecuteScalar().ToString();
            frm.NumeRaport = "RegistruCasa.rdlc";
            if(cmp=="1")
                frm.NumeRaport = "RegistruCasaCompact.rdlc";
            frm.dataloadHandler += new LoadDataHandler(frm_dataloadHandler);

            frm.AddDataSource("ESRPDataSet_BalconSetup", listBS[0]);
            frm.AddDataSource("balcon_GenRegistruCasa", listBS[1]);

            frm.AddParameter("Linia1", linia1, true);
            frm.AddParameter("Linia2", linia2, true);

            frm.AddParameter("DebitInitial", sdf.debInit, true);
            frm.AddParameter("CreditInitial", sdf.creInit, true);
            frm.AddParameter("DebitPrecedent", sdf.debPrec, true);
            frm.AddParameter("CreditPrecedent", sdf.crePrec, true);
            frm.AddParameter("RulajDebit", sdf.debCurent, true);
            frm.AddParameter("RulajCredit", sdf.creCurent, true);
            frm.AddParameter("TotalSumeDebit", sdf.totalDeb, true);
            frm.AddParameter("TotalSumeCredit", sdf.totalCre, true);
            cmd.CommandText = "SELECT [Valoare] FROM [ParamListe] WHERE COD='ACC' AND [User]=system_user AND [Host]=host_name() AND IDLista=" + m_IdLista.ToString() + " AND [CodUnitate]=" + ModuleInfo.CodUnitate.ToString();
            Object oplc = cmd.ExecuteScalar();
            frm.AddParameter("ContCoresp", (oplc!=null && oplc!=DBNull.Value && oplc.ToString()=="1")?"True":"False", true);
            frm.AddParameter("DocumentJustificativ", (bDocumentJustifRulaj?"True":"False"),true);

            cmd.CommandText = "SELECT [Valoare] FROM [ParamListe] WHERE COD='SPZ' AND [User]=system_user AND [Host]=host_name() AND IDLista=" + m_IdLista.ToString() + " AND [CodUnitate]=" + ModuleInfo.CodUnitate.ToString();
            Object spz = cmd.ExecuteScalar();
            Boolean bPaginaPerZi = false;
            if (spz != null && spz.ToString()=="1")
                bPaginaPerZi = true;
            frm.AddParameter("PaginaPerZi", (bPaginaPerZi ? "True" : "False"), true);
            String l1s = String.Empty, l2s = String.Empty, l3s = String.Empty, l1d = String.Empty, l2d = String.Empty, l3d = String.Empty;
            Object ret = GetSetupValue("BalconSetup", "Linia1Stanga", ModuleInfo.CodUnitate, cmd.Connection);
            if (ret != null && ret != DBNull.Value)
                l1s = ret.ToString();
            ret = GetSetupValue("BalconSetup", "Linia2Stanga", ModuleInfo.CodUnitate, cmd.Connection);
            if (ret != null && ret != DBNull.Value)
                l2s = ret.ToString();
            ret = GetSetupValue("BalconSetup", "Linia3Stanga", ModuleInfo.CodUnitate, cmd.Connection);
            if (ret != null && ret != DBNull.Value)
                l3s = ret.ToString();
            ret = GetSetupValue("BalconSetup", "Linia1Dreapta", ModuleInfo.CodUnitate, cmd.Connection);
            if (ret != null && ret != DBNull.Value)
                l1d = ret.ToString();
            ret = GetSetupValue("BalconSetup", "Linia2Dreapta", ModuleInfo.CodUnitate, cmd.Connection);
            if (ret != null && ret != DBNull.Value)
                l2d = ret.ToString();
            ret = GetSetupValue("BalconSetup", "Linia3Dreapta", ModuleInfo.CodUnitate, cmd.Connection);
            if (ret != null && ret != DBNull.Value)
                l3d = ret.ToString();

            frm.AddParameter("Antet1Stanga", l1s, true);
            frm.AddParameter("Antet2Stanga", l2s, true);
            frm.AddParameter("Antet3Stanga", l3s, true);
            frm.AddParameter("Antet1Dreapta", l1d, true);
            frm.AddParameter("Antet2Dreapta", l1d, true);
            frm.AddParameter("Antet3Dreapta", l1d, true);
            frm.AddParameter("DataInTitlu", (bDataInTitlu ? "True" : "False"), true);
            frm.AddParameter("GroupDataDocJust",  "False", true);
            
            frm.SetWindowFormat(true);
            InchideConexiune(cmd.Connection);
            return true;
        }

        private void ExtrasDeCont(PreviewRaportFrm frm, ESRPDataSet eSRPDS, String Titlu)
        {
            SqlCommand cmd = new SqlCommand("", DeschideConexiune(workConnString));
            cmd.CommandText = "SELECT [Valoare] FROM [ParamListe] WHERE COD='DLD' AND [User]=system_user AND [Host]=host_name() AND IDLista=" + m_IdLista.ToString() + " AND [CodUnitate]=" + ModuleInfo.CodUnitate.ToString();
            String objDte = cmd.ExecuteScalar().ToString();
            String filtruData = String.Empty;

            DateTime dte = DateTime.MinValue, dt = DateTime.MaxValue;
            if (objDte != String.Empty)
            {
                dte = DateTime.FromOADate(Convert.ToDouble(objDte));
                filtruData = " DataDoc >= @DataStart ";
            }


            cmd.CommandText = "SELECT [Valoare] FROM [ParamListe] WHERE COD='PLD' AND [User]=system_user AND [Host]=host_name() AND IDLista=" + m_IdLista.ToString() + " AND [CodUnitate]=" + ModuleInfo.CodUnitate.ToString();
            String objDt = cmd.ExecuteScalar().ToString();
            if (objDt != String.Empty)
            {
                dt = DateTime.FromOADate(Convert.ToDouble(objDt));
                if (filtruData != String.Empty)
                    filtruData += "AND ";
                filtruData += " DataDoc <= @DataEnd ";
            }

            String linia1 = Titlu + " ", linia2 = String.Empty; //+ tipJurn;
            linia1 += " in intervalul " + dte.ToString("d",cultureRO) + " - " + dt.ToString("d",cultureRO);

            cmd.CommandText = "SELECT [Valoare] FROM [ParamListe] WHERE COD='DLC' AND [User]=system_user AND [Host]=host_name() AND IDLista=" + m_IdLista.ToString() + " AND [CodUnitate]=" + ModuleInfo.CodUnitate.ToString();
            Object odlc = cmd.ExecuteScalar();
            String dlc = String.Empty;
            if (odlc != null) dlc = odlc.ToString();

            cmd.CommandText = "SELECT [Valoare] FROM [ParamListe] WHERE COD='PLC' AND [User]=system_user AND [Host]=host_name() AND IDLista=" + m_IdLista.ToString() + " AND [CodUnitate]=" + ModuleInfo.CodUnitate.ToString();
            Object oplc = cmd.ExecuteScalar();
            String plc = String.Empty;
            if (oplc != null)
                plc = oplc.ToString();
            String filtreTot = String.Empty, filtreTotSuma = String.Empty, filtreTotCredit = String.Empty;
            String filtruCont = String.Empty;
            String filtruContCredit = String.Empty;
            if (plc != String.Empty || dlc != String.Empty)
            {

                if (dlc != String.Empty)
                {
                    linia2 = "de la contul " + dlc;
                    filtruCont = " AND ContDebit >= '" + dlc + "'";
                    filtruContCredit = " AND ContCredit >= '" + dlc + "'";
                    filtreTotSuma = " AND Cont >= '" + dlc + "'";
                }
                if (plc != String.Empty)
                {
                    linia2 += " pana la contul " + plc;
                    filtruCont += " AND ContDebit <= '" + plc + "'";
                    filtruContCredit += " AND ContCredit <= '" + plc + "'";
                    filtreTotSuma += " AND Cont <= '" + plc + "'";
                    if (plc == dlc)
                    {
                        linia2 = " pentru contul " + plc;
                        filtruCont = " AND ContDebit LIKE '" + plc + "%'";
                        filtruContCredit = " AND ContCredit LIKE '" + plc + "%'";
                        filtreTotSuma = " AND Cont LIKE '" + plc + "%'";
                    }
                }


            }
            cmd.CommandText = "SELECT [IDJurnal] FROM [ParamListe] a JOIN [Jurnale] b ON b.Codificare = LTRIM(RTRIM(a.[Valoare])) " +
                    "WHERE COD='JRN' AND [User]=system_user AND [Host]=host_name() AND IDLista=" + m_IdLista.ToString() + " AND a.[CodUnitate]=" + ModuleInfo.CodUnitate.ToString();

            String sJurnal = "-1";
            if (cmd.ExecuteScalar() != null)
                sJurnal = cmd.ExecuteScalar().ToString();

            listBS.Add(new BindingSource(eSRPDS, "balcon_GenRegistruCasa"));

            //String comanda = "SELECT ContDebit,ContCredit,'D' AS Tip,NumarDoc,DataDoc,NumarNota,ValoareLei,IdJurnal,TipDocJust,NumarDocJust,DataDocJust,ExplicatiiDocJust,TipFormula,Categorie FROM NotaContabilaView WHERE [ContDebit]<>'N/A' " + " AND [CodUnitate]=" + ModuleInfo.CodUnitate.ToString();
            //String Comanda2 = "SELECT ContCredit AS ContDebit,ContDebit AS ContCredit,'C' AS Tip,NumarDoc,DataDoc,NumarNota,ValoareLei,IdJurnal,TipDocJust,NumarDocJust,DataDocJust,ExplicatiiDocJust,TipFormula,Categorie FROM NotaContabilaView WHERE [ContCredit]<>'N/A' " + " AND [CodUnitate]=" + ModuleInfo.CodUnitate.ToString();

            ///sectiunea de jurnale
            if (filtruCont != String.Empty)
            {
                filtreTot += filtruCont;
                filtreTotCredit += filtruContCredit;
            }

            SumDocFormula sdf = new SumDocFormula(cmd.Connection);
            sdf.CalcTotal(filtreTotSuma, dte, dt, Convert.ToInt16(sJurnal), ModuleInfo);

            if (sJurnal != "-1")
            {
                filtreTot += " AND [IdJurnal] = " + sJurnal;
                filtreTotCredit += " AND [IdJurnal] = " + sJurnal;
                cmd.CommandText = "SELECT [Valoare] FROM [ParamListe] WHERE COD='JRN' AND [User]=system_user AND [Host]=host_name() AND IDLista=" + m_IdLista.ToString() + " AND [CodUnitate]=" + ModuleInfo.CodUnitate.ToString();
                linia2 += " pentru " + cmd.ExecuteScalar().ToString();
            }

            /*listTA.Add(new SqlDataAdapter("[GenNotaContabilaUnion]", cmd.Connection));
            listTA[listTA.Count - 1].SelectCommand.CommandType = CommandType.StoredProcedure;
            listTA[listTA.Count - 1].SelectCommand.Parameters.Add(new SqlParameter("@cont", String.Empty));
            listTA[listTA.Count - 1].SelectCommand.Parameters.Add(new SqlParameter("@CodUnitate", Convert.ToInt16(ModuleInfo.CodUnitate)));
            listTA[listTA.Count - 1].SelectCommand.Parameters.Add(new SqlParameter("@DeLaData", dte));
            listTA[listTA.Count - 1].SelectCommand.Parameters.Add(new SqlParameter("@PanaLaData", dt));
            if (dscModule.AnArhiva == String.Empty)
                listTA[listTA.Count - 1].SelectCommand.Parameters.Add(new SqlParameter("@An", Convert.ToInt16(0)));
            else
                listTA[listTA.Count - 1].SelectCommand.Parameters.Add(new SqlParameter("@An", Convert.ToInt16(dscModule.AnArhiva)));
            listTA[listTA.Count - 1].SelectCommand.Parameters.Add(new SqlParameter("@strFilter", filtreTot));
            listTA[listTA.Count - 1].SelectCommand.Parameters.Add(new SqlParameter("@strFilter2", filtreTotCredit));
            listTA[listTA.Count - 1].SelectCommand.Parameters.Add(new SqlParameter("@strOrder", String.Empty));
            listTA[1].Fill(eSRPDS.NotaContabilaView);*/

            listTA.Add(new SqlDataAdapter("[balcon_GenRegistruCasa]", cmd.Connection));
            int indexTA = listTA.Count - 1;
            listTA[indexTA].SelectCommand.CommandType = CommandType.StoredProcedure;
            listTA[indexTA].SelectCommand.Parameters.Add(new SqlParameter("@CodUnitate", Convert.ToInt16(ModuleInfo.CodUnitate)));
            listTA[indexTA].SelectCommand.Parameters.Add(new SqlParameter("@DeLaData", dte));
            listTA[indexTA].SelectCommand.Parameters.Add(new SqlParameter("@PanaLaData", dt));
            listTA[indexTA].SelectCommand.Parameters.Add(new SqlParameter("@Cod", ""));
            listTA[indexTA].SelectCommand.Parameters.Add(new SqlParameter("@DeLaCont", dlc));
            listTA[indexTA].SelectCommand.Parameters.Add(new SqlParameter("@PanaLaCont", plc));
        
            FiltruRCCredit = filtreTotCredit;
            FiltruRCDebit = filtreTot;

            listTA[indexTA].Fill(eSRPDS.balcon_GenRegistruCasa);

            frm.NumeRaport = "RegistruCasa.rdlc";

            frm.dataloadHandler += new LoadDataHandler(frm_dataloadHandler);

            frm.AddDataSource("ESRPDataSet_BalconSetup", listBS[0]);
            frm.AddDataSource("balcon_GenRegistruCasa", listBS[1]);


            frm.AddParameter("Linia1", linia1, true);
            frm.AddParameter("Linia2", linia2, true);

            frm.AddParameter("DebitInitial", sdf.debInit, true);
            frm.AddParameter("CreditInitial", sdf.creInit, true);
            frm.AddParameter("DebitPrecedent", sdf.debPrec, true);
            frm.AddParameter("CreditPrecedent", sdf.crePrec, true);
            frm.AddParameter("RulajDebit", sdf.debCurent, true);
            frm.AddParameter("RulajCredit", sdf.creCurent, true);
            frm.AddParameter("TotalSumeDebit", sdf.totalDeb, true);
            frm.AddParameter("TotalSumeCredit", sdf.totalCre, true);
            cmd.CommandText = "SELECT [Valoare] FROM [ParamListe] WHERE COD='ACC' AND [User]=system_user AND [Host]=host_name() AND IDLista=" + m_IdLista.ToString() + " AND [CodUnitate]=" + ModuleInfo.CodUnitate.ToString();
            oplc = cmd.ExecuteScalar();
            frm.AddParameter("ContCoresp", (oplc != null && oplc != DBNull.Value && oplc.ToString() == "1") ? "True" : "False", true);
            //frm.AddParameter("Debit", Debit == "Debit" ? "True" : "False", true);
            frm.AddParameter("DocumentJustificativ", (bDocumentJustifRulaj ? "True" : "False"), true);

            cmd.CommandText = "SELECT [Valoare] FROM [ParamListe] WHERE COD='SPZ' AND [User]=system_user AND [Host]=host_name() AND IDLista=" + m_IdLista.ToString() + " AND [CodUnitate]=" + ModuleInfo.CodUnitate.ToString();
            Object spz = cmd.ExecuteScalar();
            Boolean bPaginaPerZi = false;
            if (spz != null && spz.ToString() == "1")
                bPaginaPerZi = true;
            String l1s=String.Empty, l2s=String.Empty, l3s=String.Empty, l1d=String.Empty, l2d=String.Empty, l3d=String.Empty;
            frm.AddParameter("PaginaPerZi", (bPaginaPerZi ? "True" : "False"), true);
            Object ret = GetSetupValue("BalconSetup", "Linia1Stanga", ModuleInfo.CodUnitate, cmd.Connection);
            if (ret != null && ret != DBNull.Value)
                l1s = ret.ToString();
            ret = GetSetupValue("BalconSetup", "Linia2Stanga", ModuleInfo.CodUnitate, cmd.Connection);
            if (ret != null && ret != DBNull.Value)
                l2s = ret.ToString();
            ret = GetSetupValue("BalconSetup", "Linia3Stanga", ModuleInfo.CodUnitate, cmd.Connection);
            if (ret != null && ret != DBNull.Value)
                l3s = ret.ToString();
            ret = GetSetupValue("BalconSetup", "Linia1Dreapta", ModuleInfo.CodUnitate, cmd.Connection);
            if (ret != null && ret != DBNull.Value)
                l1d = ret.ToString();
            ret = GetSetupValue("BalconSetup", "Linia2Dreapta", ModuleInfo.CodUnitate, cmd.Connection);
            if (ret != null && ret != DBNull.Value)
                l2d = ret.ToString();
            ret = GetSetupValue("BalconSetup", "Linia3Dreapta", ModuleInfo.CodUnitate, cmd.Connection);
            if (ret != null && ret != DBNull.Value)
                l3d = ret.ToString();
            frm.AddParameter("Antet1Stanga", l1s, true);
            frm.AddParameter("Antet2Stanga", l2s, true);
            frm.AddParameter("Antet3Stanga", l3s, true);
            frm.AddParameter("Antet1Dreapta", l1d, true);
            frm.AddParameter("Antet2Dreapta", l1d, true);
            frm.AddParameter("Antet3Dreapta", l1d, true);
            frm.AddParameter("DataInTitlu", "False", true);
            frm.AddParameter("GroupDataDocJust",  "False", true);
            frm.SetWindowFormat(true);
            InchideConexiune(cmd.Connection);
        }

        private Boolean GenereazaBilant(BindingSource bs, DataTable bdt)
        { 
             
            SqlCommand cmd = new SqlCommand("GenListaBilant", DeschideConexiune(workConnString));
            if(m_IdLista == 15)
                cmd.CommandText = "GenListaVenituriSiCheltuieli";
            if (m_IdLista == 14)
                cmd.CommandText = "GenListaRezultat";

            cmd.CommandType = CommandType.StoredProcedure;
            SqlDataReader dataR =  cmd.ExecuteReader();
            if (!dataR.HasRows)
            {
                dataR.Close();
                InchideConexiune(cmd.Connection);
                MessageBox.Show("Nu este posibila generarea balantei!","Eroare",MessageBoxButtons.OK,MessageBoxIcon.Stop);
                return false;
            }
            //SqlDataAdapter ta = new SqlDataAdapter();
            DataTable dt = new DataTable("ListaRezultat");
            dt.Load(dataR);
            dataR.Close();
            InchideConexiune(cmd.Connection);

            ///seteaza cheia primara pe conturi
            DataColumn[] keys = {dt.Columns["Cont"]};
            DataColumn[] keys2 = { bdt.Columns["codfix"], bdt.Columns["CodUnitate"] };

            dt.PrimaryKey =  keys;
            bdt.PrimaryKey = keys2;
            
            
            bs.Sort = "eval ASC,row ASC";

            for (int i = 0; i < bs.Count; i++)
            {
                DataRowView dr = (DataRowView)bs.Current;
                if (dr["coltypei"].ToString().ToUpper() == "T")
                {
                    dr["SoldIP"] = dr["soldi"];
                }
                else
                if (dr["coltypei"].ToString().ToUpper() == "S")
                {
                    dr["SoldIP"] = CalcCellValue2(dr["soldi"].ToString(), dt);
                }
                else
                if (dr["coltypei"].ToString().ToUpper() == "F")
                {
                    dr["SoldIP"] = CalcFormulaValue2(dr["soldi"].ToString(), bdt);
                }


                if (dr["coltypef"].ToString().ToUpper() == "T")
                {
                    dr["SoldSP"] = dr["soldf"];
                }
                else
                    if (dr["coltypef"].ToString().ToUpper() == "S")
                {
                    dr["SoldSP"] = CalcCellValue2(dr["soldf"].ToString(), dt);
                }
                else
                if (dr["coltypef"].ToString().ToUpper() == "F")
                {
                    dr["SoldSP"] = CalcFormulaValue2(dr["soldf"].ToString(), bdt);
                    
                }
                bs.MoveNext();
            }
            bs.MoveFirst();
            bs.Filter = "";
            return true;	

        }

        private String CalcCellValue2(String textp, DataTable dt)
        {
            
	        Decimal	vResult= Decimal.Zero;
            String temp = String.Empty;

            MatchCollection m = Regex.Matches(textp.ToUpper(),
                @"(\s*(?<semn>\+|\-)*(?<prefix>ISOLD|IDSOLD|ICSOLD|FSOLD|FDSOLD|FCSOLD|RDEB|RCRE)+(?<cont>[\d]+\.*[\d]*)\s*)");

            foreach (Match mp in m)
            {
                if (mp.Success == true)
                {
                    temp += mp.Groups["semn"].ToString() + mp.Groups["prefix"].ToString() + mp.Groups["cont"].ToString() + "|";
                    DataRow dr = dt.Rows.Find(mp.Groups["cont"].ToString());
                    Decimal minus = Decimal.One;
                    if (mp.Groups["semn"].ToString() == "-")
                        minus = -Decimal.One;
                    if (dr != null)
                    {
                        if (mp.Groups["prefix"].ToString() == "ISOLD")
                        {
                            vResult += minus*Convert.ToDecimal(dr["SoldInit"].ToString());
                        }
                        if (mp.Groups["prefix"].ToString() == "IDSOLD")
                        {
                            vResult += minus * Convert.ToDecimal(dr["DebInit"].ToString());
                        }
                        if (mp.Groups["prefix"].ToString() == "ICSOLD")
                        {
                            vResult += minus * Convert.ToDecimal(dr["CreInit"].ToString());
                        }

                        if (mp.Groups["prefix"].ToString() == "FSOLD")
                        {
                            vResult += minus * Convert.ToDecimal(dr["SoldTotal"].ToString());
                        }
                        if (mp.Groups["prefix"].ToString() == "FDSOLD")
                        {
                            vResult += minus * Convert.ToDecimal(dr["SoldTotalDeb"].ToString());
                        }
                        if (mp.Groups["prefix"].ToString() == "FCSOLD")
                        {
                            vResult += minus * Convert.ToDecimal(dr["SoldTotalCre"].ToString());
                        }
                        if (mp.Groups["prefix"].ToString() == "RDEB")
                        {
                            vResult += minus * Convert.ToDecimal(dr["DebRul"].ToString());
                        }
                        if (mp.Groups["prefix"].ToString() == "RCRE")
                        {
                            vResult += minus * Convert.ToDecimal(dr["CreRul"].ToString());
                        }

                    }
                }

            }
            return vResult.ToString("N0");
    }

        private String CalcFormulaValue2(String sFormula, DataTable bdt)
        {
	        Decimal ret = Decimal.Zero;
            Boolean dacaPozitiv = false;
            sFormula = sFormula.Replace("=", String.Empty);
            if (sFormula.Contains("[POZ]"))
            {
                sFormula = sFormula.Replace("[POZ]", String.Empty);
                dacaPozitiv = true;
            }
            MatchCollection m = Regex.Matches(sFormula.ToUpper(),
                @"(\s*(?<semn>\+|\-)*(?<prefix>C|D)+(?<rand>[\d]+)\s*)");

            foreach (Match mp in m)                 
            {
                if (mp.Success == true)
                {
                    Object[] keysa = { Convert.ToInt32(mp.Groups["rand"].ToString()), ModuleInfo.CodUnitate };
                    DataRow dr = bdt.Rows.Find(keysa);
                    Decimal minus = Decimal.One;
                    if (mp.Groups["semn"].ToString() == "-")
                        minus = -Decimal.One;
                    if (dr != null)
                    {
                        if (mp.Groups["prefix"].ToString() == "C")
                        {
                            String cv1 = dr["SoldIP"].ToString();
                            if (cv1 == String.Empty)
                                cv1 = "0";
                            ret += minus * Convert.ToDecimal(cv1);
                        }
                        if (mp.Groups["prefix"].ToString() == "D")
                        {
                            String cv1 = dr["SoldSP"].ToString();
                            if (cv1 == String.Empty)
                                cv1 = "0";
                            ret += minus * Convert.ToDecimal(cv1);
                        }
                    }
                }

            }      
            if(dacaPozitiv && ret<=Decimal.Zero)
                return Decimal.Zero.ToString("N0");
	        return ret.ToString("N0");
        }

        private void FormatGrid(DataGridView dgv,String NumeColoana/*valoare2Column*/,String TipColoana,String DenumireColoana,String VIColoana,String ValoareColoana)
        {
            //valoriDGV.Columns[NumeColoana].CellTemplate = null;
            foreach (DataGridViewRow dr in dgv.Rows)
            {
                Int16 RowIndex = (Int16)dr.Index;
                if (dr.Cells[TipColoana].Value.ToString().Trim() == "S")
                {
                    //DataGridViewTextBoxCell oldCell = (DataGridViewTextBoxCell)dr.Cells[NumeColoana];
                    DataGridViewComboBoxCell ctrlCB = new DataGridViewComboBoxCell();
                    ctrlCB.ValueType = typeof(String);
                    ctrlCB.DisplayStyle = DataGridViewComboBoxDisplayStyle.ComboBox;
                    String Optiuni = dr.Cells[VIColoana].Value.ToString();
                    int pos=Optiuni.IndexOf('|');
                    while (pos >= 0)
                    {
                        String val1 = Optiuni.Substring(0, pos);
                        Optiuni = Optiuni.Substring(pos+1);
                        ctrlCB.Items.Add(val1);
                        pos = Optiuni.IndexOf('|');
                        ///dupa ultima optiune s-ar putea sa nu fie |
                        ///
                        if (pos == -1 && Optiuni.Length > 0)
                        {
                            pos = Optiuni.Length;
                            Optiuni += "|";
                        }
                    }
                    ctrlCB.Value = dr.Cells[ValoareColoana].Value.ToString();
                    ctrlCB.DisplayStyleForCurrentCellOnly = false;
                    dgv[NumeColoana,dr.Index] = ctrlCB;
                    continue;
                }
                if (dr.Cells[TipColoana].Value.ToString().Trim() == "B")
                {
                    object val = dr.Cells[ValoareColoana].Value;
                    dr.Cells[NumeColoana] = new DataGridViewCheckBoxCell(false);
                    dr.Cells[NumeColoana].ValueType = typeof(Boolean);
                    ((DataGridViewCheckBoxCell)dr.Cells[NumeColoana]).Value = 
                        dr.Cells[ValoareColoana].Value.ToString()== "1";
                    ((DataGridViewCheckBoxCell)dr.Cells[NumeColoana]).ThreeState = false;
                    //((DataGridViewCheckBoxCell)dr.Cells[NumeColoana]).OnClick += new EventHandler(OnClickCheckBox);
                    continue;
                }
                if (dr.Cells[TipColoana].Value.ToString().Trim() == "D")
                {
                    object val = dr.Cells[ValoareColoana].Value;
                    dr.Cells[NumeColoana] = new DataGridViewCalendarCell();

                    //((DataGridViewCalendarCell)dr.Cells[NumeColoana]). = DateTimePickerFormat.Custom;
                    //panaLaDataDTP.CustomFormat = Application.CurrentCulture.DateTimeFormat.ShortDatePattern;
                    //((DataGridViewCheckBoxCell)dr.Cells[NumeColoana]). = 1;
                    dr.Cells[NumeColoana].ValueType = typeof(DateTime);
                    if (ModuleInfo.AnArhiva == String.Empty)
                    {
                        DateTime EmptyDate = new DateTime(AnulCurent, LunaCurenta, 1).AddMonths(1).AddDays(-1);
                        if (dr.Cells[ValoareColoana].Value.ToString().Trim() == String.Empty)
                            dr.Cells[NumeColoana].Value = EmptyDate;
                        else
                        {
                            DateTime valSalvata = DateTime.FromOADate(Convert.ToDouble(dr.Cells[ValoareColoana].Value));
                            dr.Cells[NumeColoana].Value = valSalvata;
                            if (valSalvata.Year != EmptyDate.Year)
                                dr.Cells[NumeColoana].Value = EmptyDate;
                        }
                        ((DataGridViewCalendarCell)dr.Cells[NumeColoana]).MaxValue = new DateTime(AnulCurent, LunaCurenta, 1).AddMonths(1).AddDays(-1);
                    }
                    else
                    {
                        DateTime EmptyDate = new DateTime(Convert.ToInt32(ModuleInfo.AnArhiva), LunaCurenta, 1).AddMonths(1).AddDays(-1);
                        if (dr.Cells[ValoareColoana].Value.ToString().Trim() == String.Empty)
                            dr.Cells[NumeColoana].Value = EmptyDate;
                        else
                        {
                            DateTime valSalvata = DateTime.FromOADate(Convert.ToDouble(dr.Cells[ValoareColoana].Value));
                            dr.Cells[NumeColoana].Value = valSalvata;
                            if (valSalvata > EmptyDate)
                                dr.Cells[NumeColoana].Value = EmptyDate;
                        }                    
                    }
                    //((RelationTextBox.DataGridViewCalendarCell)dr.Cells[ValoareColoana]).MaxValue = new DateTime(AnulCurent, LunaCurenta, 1).AddMonths(1).AddDays(-1);
                    continue;
                
                }
                if (dr.Cells[TipColoana].Value.ToString().Trim() == "R")
                {
                    object val = dr.Cells[ValoareColoana].Value;
                    dr.Cells[NumeColoana] = new RelationTextBox.RelationTextBoxCell();
                    //((DataGridViewCheckBoxCell)dr.Cells[NumeColoana]). = 1;
                    if (dr.Cells[DenumireColoana].Value.ToString().ToLower().Contains("cont"))
                        ((RelationTextBox.RelationTextBoxCell)dr.Cells[NumeColoana]).MyButtonClick = RezumatConturi;

                    if (dr.Cells[DenumireColoana].Value.ToString().ToLower().Contains("sursa"))
                        ((RelationTextBox.RelationTextBoxCell)dr.Cells[NumeColoana]).MyButtonClick = RezumatSurseFinantare;

                    if (dr.Cells[DenumireColoana].Value.ToString().ToLower().Contains("jurnal") && dscModule.eUnitateBugetara)
                    {
                        ///daca e unitate bugetara trece in loc de jurnal.. capitol
                        ///
                        String text = dr.Cells[DenumireColoana].Value.ToString();
                        dr.Cells[DenumireColoana].Value = text.Replace("Jurnal", "Capitol");
                    }

                    

                    if (dr.Cells[DenumireColoana].Value.ToString().ToLower().Contains("jurnal") || dr.Cells[DenumireColoana].Value.ToString().ToLower().Contains("capitol"))
                        ((RelationTextBox.RelationTextBoxCell)dr.Cells[NumeColoana]).MyButtonClick = RezumatJurnale;
                    if (dr.Cells[DenumireColoana].Value.ToString().ToLower().Contains("moneda"))
                    {
                        ((RelationTextBox.RelationTextBoxCell)dr.Cells[NumeColoana]).MyButtonClick = RezumatMoneda;
                        ((RelationTextBox.RelationTextBoxCell)dr.Cells[NumeColoana]).ReadOnly = true;
                    }

                    if (dr.Cells[DenumireColoana].Value.ToString().ToLower().Contains("articol"))
                    {
                        ((RelationTextBox.RelationTextBoxCell)dr.Cells[NumeColoana]).MyButtonClick = RezumatArticol;
                    }

                    dr.Cells[NumeColoana].ValueType = typeof(String);
                    dr.Cells[NumeColoana].Value = dr.Cells[ValoareColoana].Value;
                    continue;
                }
            }
        }

        private void SelectList(Int16 idl,SqlConnection con)
        {
            try
            {
                this.paramListeTableAdapter.Connection = con;
                this.paramListeTableAdapter.FillByParamList(this.eSRPDataSet.ParamListe, ((short)idl), ModuleInfo.CodUnitate);
                paramListeBindingSource.Sort = "[NrCrt]";
                if (paramListeBindingSource.Count == 0)
                {
                    SqlCommand cmd = new SqlCommand("", con);
                    cmd.CommandText = "INSERT INTO [ParamListe] ([CodUnitate],[IDLista],[Cod],[NrCrt],[Denumire],[Valoare],[ValoareImplicita],[Tip],[Validare],[SelRezumat],[User],[Host]) " +
                    " (SELECT " + ModuleInfo.CodUnitate.ToString() + ",[IDLista],[Cod],[NrCrt],[Denumire],[Valoare],[ValoareImplicita],[Tip],[Validare],[SelRezumat],system_user,host_name() " +
                    " FROM [ParamListe] a WHERE [User] ='0' AND Host='0' AND [CodUnitate]=0 AND NOT EXISTS(SELECT * FROM [ParamListe] b WHERE b.[CodUnitate]=" + ModuleInfo.CodUnitate.ToString() + " AND b.[user]=system_user and b.[host]=host_name() and b.[Cod]=a.[Cod] and a.[IdLista]=b.[IdLista]))";
                    cmd.ExecuteNonQuery();
                    this.paramListeTableAdapter.FillByParamList(this.eSRPDataSet.ParamListe, ((short)idl), ModuleInfo.CodUnitate);
                }
            }
            catch (System.Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.Message);
            }

        }

        override public void SetCurentUnit(short vCodUnitate,SqlConnection con)
        {
            this.ModuleInfo.CodUnitate = vCodUnitate;
            valoriDGV.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None;
            Object retObj = GetSetupValue("BalconSetup", "LunaCurenta", ModuleInfo.CodUnitate, con);
            if (retObj != null && retObj != DBNull.Value)
                LunaCurenta = Convert.ToInt32(retObj);
            if (LunaCurenta == 0)
                LunaCurenta = DateTime.Now.Month;
            retObj = GetSetupValue("BalconSetup", "AnCurent", ModuleInfo.CodUnitate, con);
            if (retObj != null && retObj != DBNull.Value)
                AnulCurent = Convert.ToInt32(retObj);
            if (AnulCurent == 0)
                AnulCurent = DateTime.Now.Year;
            SelectList(m_IdLista,con);
        }

        override public void SetCurentMonth(short vCodUnitate)
        {
           // Setup(conn);
        }
        /// <summary>
        /// cand se apasa enter, controlul activ este luna, anul
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        override public void toolStripLabelAnLuna_Click(object sender, EventArgs e)
        {

        }

        private Boolean Bilant(PreviewRaportFrm frm, ESRPDataSet eSRPDS)      
        {
            TipLista = 0;
            String tabela = "BilantView";
            String ignora = "3";
            String linia1 = "Bilant";
            SqlCommand cmd = new SqlCommand("", DeschideConexiune(workConnString));
            DateTime dt = DateTime.Now;
            if (m_IdLista == 14)
            {
                linia1 = "Contul de rezultat patrimonial";
                tabela = "RezultatPatrimonial";
                ignora = "3";
            }
            if (m_IdLista == 15)
            {
                linia1 = "Situatia veniturilor si cheltuielilor";
                tabela = "VenituriSiCheltuieliView";
                ignora = "1";
            }

            cmd.CommandText = "SELECT [Valoare] FROM [ParamListe] WHERE COD='LDT' AND [User]=system_user AND [Host]=host_name() AND IDLista=" + m_IdLista.ToString() + " AND [CodUnitate]=" + ModuleInfo.CodUnitate.ToString();
            String obj = cmd.ExecuteScalar().ToString();

            if (obj != String.Empty)
                dt = DateTime.FromOADate(Convert.ToDouble(obj));
            String linia2 = " la data " + dt.ToString("d",cultureRO);


            listTA.Add(new SqlDataAdapter("SELECT * FROM " + tabela + " WHERE row >=" + ignora + " AND [CodUnitate]=" + ModuleInfo.CodUnitate.ToString() 
                , cmd.Connection));
            
            if (m_IdLista == 15)
            {
                listTA[1].SelectCommand.CommandText += " ORDER BY [CodFix]";
            }
            else
                listTA[1].SelectCommand.CommandText += " ORDER BY [Cod]";

            listBS.Add(new BindingSource(eSRPDS, "BilantView"));
            listTA[1].SelectCommand.CommandType = CommandType.Text;
            listTA[1].Fill(eSRPDS.BilantView);
            if (!GenereazaBilant(listBS[1], eSRPDS.BilantView))
                return false;
            //listBS[1].Sort = "cod"; --nu are efect
            if (m_IdLista == 8)
            {
                frm.NumeRaport = "Bilant.rdlc";
            }
            if (m_IdLista == 14)
            {
                 frm.NumeRaport = "RezultatPatrimonial.rdlc";
            }
            if (m_IdLista == 15)
            {
                 frm.NumeRaport = "VenituriSiCheltuieli.rdlc";
                 //listBS[1].Sort = "codfix"; - nu are efect
            }


            
            frm.AddDataSource("TabelaDescriere", listBS[1]);
            frm.AddDataSource("ESRPDataSet_BalconSetup", listBS[0]);
            frm.AddParameter("Linia1", linia1, true);
            frm.AddParameter("Linia2", linia2, true);

            cmd.CommandText = "SELECT COUNT(*) FROM [SemnaturiListe] WHERE  IDLista=" + m_IdLista + " AND [TipLista]=" + TipLista.ToString();
            Boolean eSemnaturi = Convert.ToInt32(cmd.ExecuteScalar()) != 0;
            frm.AddParameter("Semnaturi", eSemnaturi ? "True" : "False", true);
            frm.dataloadHandler += new LoadDataHandler(balanta_dataloadHandler);
            frm.SetWindowFormat(true);
            return true;

       }

        private void RapoarteFrm_Shown(object sender, EventArgs e)
        {
            FormatGrid(valoriDGV, "valoare2Column", "tipColumn", "denumireColumn", "valoareImplicitaColumn", "valoareColumn");
        }

    }

    public class SumDocFormula
    {
        private SqlConnection mConn = null;
        public SumDocFormula(SqlConnection conn) 
        {
            Trace.Assert(conn!=null,"Conexiune inexistenta");
            mConn = conn;
        }
    	public String debInit = "0.00";
        public String creInit = "0.00";
        public String debPrec = "0.00";
        public String crePrec = "0.00";
        public String debCurent = "0.00";
        public String creCurent = "0.00";
        public String rulajDeb = "0.00";
        public String rulajCre = "0.00";
        public String totalDeb = "0.00";
        public String totalCre = "0.00";
        public String SoldPrecDeb = "0.00";
        public String SoldPrecCre = "0.00";
    
        public String[] GetBalantaArray()
        { 
            List<String> ret = new List<String>(10);
            ret.Add(debInit);
            ret.Add(creInit);
            ret.Add(debPrec);
            ret.Add(crePrec);
            ret.Add(debCurent);
            ret.Add(creCurent);
            ret.Add(rulajDeb);
            ret.Add(rulajCre);
            ret.Add(totalDeb);
            ret.Add(totalCre);
            return ret.ToArray();
        }

        public Boolean CalcTotal(String filtru, DateTime dst, DateTime ded, String idJurnals, ModuleClass mi, String filtruNote = "")
        {
            SqlCommand cmd = new SqlCommand("", mConn);
            Object obj = null;
            Int16 codValuta = 0; /*codValuta.ToString(),modelContabil= smodelContabil.ToString();*/
            String strValoare = string.Empty;
            if (codValuta == 0)
                strValoare = "f.ValoareLei";
            else
                strValoare = "f.ValoareValuta";


            ///daca a fost selectat un interval se calculeaza rulajul precedent
            Boolean bData1 = ded != null;
            //prima zi a lunii
            if (dst == DateTime.MinValue)
                dst = new DateTime(ded.Year, ded.Month, 1);

            Decimal dCalcPrec = Decimal.Zero, cCalcPrec = Decimal.Zero, dDebPrec = Decimal.Zero, dCrePrec = Decimal.Zero;
            String prefix = String.Empty;
            String filtruArhiva = String.Empty;
            String filtruArhivaC = String.Empty;
            if (mi.AnArhiva != String.Empty)
            {
                prefix = "arh";
                filtruArhiva = " AND d.An =c.An AND d.An=" + mi.AnArhiva;
                filtruArhivaC = " AND c.An=" + mi.AnArhiva;
            }
            if (bData1)
            {
                cmd.CommandText = "SELECT SUM(f.[ValoareLei]) FROM " + prefix + "RulajeDoc d JOIN " + prefix + "Rulaje f ON d.IDDocument=f.IDDocument JOIN [" + prefix + "Conturi] c ON f.[ContDebit]=c.[Cont]  AND c.[CodUnitate]=D.[CodUnitate]  WHERE " +
                    "d.DataDoc < @DataDoc AND ContCredit <> 'N/A' " + filtruArhiva + " AND ContDebit <> 'N/A' AND c.[CodUnitate]=" + mi.CodUnitate.ToString() + " " + filtru;
                if (idJurnals != String.Empty)
                    cmd.CommandText += " AND [IdJurnal] in (" + idJurnals + ")";
                if (filtruNote!=String.Empty)
                    cmd.CommandText += " AND [NumarNota] not in (" + filtruNote + ")";
                cmd.Parameters.Add(new SqlParameter("DataDoc", dst));
                obj = cmd.ExecuteScalar();
                if (obj != null && obj != DBNull.Value)
                    dCalcPrec = Convert.ToDecimal(obj);
            }

            cmd.CommandText = "SELECT SUM(DebitInitial) DebitInitial FROM [" + prefix + "Conturi] C " +
                "WHERE Terminal=1 AND Cont <>'N/A' " + filtruArhivaC + " AND [CodUnitate]=" + mi.CodUnitate.ToString() + " " + filtru;

            obj = cmd.ExecuteScalar();
            if (obj != null && obj != DBNull.Value)
                debInit = Convert.ToDecimal(obj).ToString("N2");

            cmd.CommandText = "SELECT SUM(DebitPrecedent) DebitPrecedent  FROM [" + prefix + "Conturi]  c " +
                " WHERE Terminal=1 AND Cont <>'N/A' " + filtruArhivaC + " AND [CodUnitate]=" + mi.CodUnitate.ToString() + " " + filtru;
            obj = cmd.ExecuteScalar();
            if (obj != null && obj != DBNull.Value)
                dDebPrec = Convert.ToDecimal(obj);
            dDebPrec += dCalcPrec;
            debPrec = dDebPrec.ToString("N2");


            if (bData1)
            {
                cmd.CommandText = "SELECT SUM(f.[ValoareLei]) FROM " + prefix + "RulajeDoc d JOIN " + prefix + "Rulaje f ON d.IDDocument=f.IDDocument  JOIN [" + prefix + "Conturi] c ON " +
                 " f.[ContCredit]=c.[Cont]  AND c.[CodUnitate]=D.[CodUnitate]  WHERE d.DataDoc < @DataDoc AND ContDebit <> 'N/A' " + filtruArhiva + " AND ContCredit <> 'N/A'  AND c.[CodUnitate]=" + mi.CodUnitate.ToString() + " " + filtru;
                //cmd.Parameters.Add(new SqlParameter("DataDoc", ded));
                /// a fost adaugat deja in if-ul anterior
                /// 
                if (idJurnals != String.Empty)
                    cmd.CommandText += " AND [IdJurnal] in (" + idJurnals + ")";
                if (filtruNote != String.Empty)
                    cmd.CommandText += " AND [NumarNota] not in (" + filtruNote + ")";

                obj = cmd.ExecuteScalar();
                if (obj != null && obj != DBNull.Value)
                    cCalcPrec = Convert.ToDecimal(obj);
            }

            cmd.CommandText = "SELECT SUM(CreditInitial) CreditInitial FROM [" + prefix + "Conturi]  C " +
                " WHERE Terminal=1 AND Cont <>'N/A'  " + filtruArhivaC + " AND [CodUnitate]=" + mi.CodUnitate.ToString() + " " + filtru;
            obj = cmd.ExecuteScalar();
            if (obj != null && obj != DBNull.Value)
                creInit = Convert.ToDecimal(obj).ToString("N2");

            cmd.CommandText = "SELECT SUM(CreditPrecedent) CreditPrecedent  FROM [" + prefix + "Conturi]  C " +
                " WHERE Terminal=1 AND Cont <>'N/A' " + filtruArhivaC + " AND [CodUnitate]=" + mi.CodUnitate.ToString() + " " + filtru;

            obj = cmd.ExecuteScalar();
            if (obj != null && obj != DBNull.Value)
                dCrePrec = Convert.ToDecimal(obj);
            dCrePrec += cCalcPrec;
            crePrec = dCrePrec.ToString("N2");


            cmd.CommandText = "SELECT SUM(" + strValoare + ") totalDebit FROM " + prefix + "RulajeDoc D  JOIN " + prefix + "Rulaje F ON D.IDDocument=F.IDDocument JOIN " + prefix + "Conturi C ON  F.ContDebit=C.Cont  AND c.[CodUnitate]=D.[CodUnitate]  WHERE  C.Cont<>'N/A' " + filtruArhiva + " AND C.Terminal=1  AND C.[CodUnitate]=" + mi.CodUnitate.ToString() + " "
                + filtru;
            if (idJurnals != String.Empty)
                cmd.CommandText += " AND [IdJurnal] in (" + idJurnals + ")";
            if (filtruNote != String.Empty)
                cmd.CommandText += " AND [NumarNota] not in (" + filtruNote + ")";

            cmd.Parameters.Clear();
            cmd.CommandText += " AND D.DataDoc >= @DataDocStart";
            cmd.Parameters.Add(new SqlParameter("DataDocStart", dst));
            cmd.CommandText += " AND D.DataDoc <= @DataDocEnd";
            cmd.Parameters.Add(new SqlParameter("DataDocEnd", ded));

            obj = cmd.ExecuteScalar();
            if (obj != null && obj != DBNull.Value)
                debCurent = Convert.ToDecimal(obj).ToString("N2");


            cmd.CommandText = "SELECT SUM(" + strValoare + ") totalCredit FROM " + prefix + "RulajeDoc D  JOIN " + prefix + "Rulaje F ON D.IDDocument=F.IDDocument JOIN " + prefix + "Conturi C ON  F.ContCredit=C.Cont  AND c.[CodUnitate]=D.[CodUnitate]  WHERE  C.Cont<>'N/A' " + filtruArhiva + " AND C.Terminal=1  AND C.[CodUnitate]=" + mi.CodUnitate.ToString() + " "
                + filtru;
            if (idJurnals != String.Empty)
                cmd.CommandText += " AND [IdJurnal] in (" + idJurnals + ")";
            if (filtruNote != String.Empty)
                cmd.CommandText += " AND [NumarNota] not in (" + filtruNote + ")";

            cmd.Parameters.Clear();
            cmd.CommandText += " AND D.DataDoc >= @DataDocStart";
            cmd.Parameters.Add(new SqlParameter("DataDocStart", dst));
            cmd.CommandText += " AND D.DataDoc <= @DataDocEnd";
            cmd.Parameters.Add(new SqlParameter("DataDocEnd", ded));
            obj = cmd.ExecuteScalar();
            if (obj != null && obj != DBNull.Value)
                creCurent = Convert.ToDecimal(obj).ToString("N2");

            ///calcularea sumelor soldurilor finale
            ///nu este acelasi lucru cu sumele totale
            ///

            Decimal dC = Convert.ToDecimal(debCurent), dP = Convert.ToDecimal(debPrec), cC = Convert.ToDecimal(creCurent), cP = Convert.ToDecimal(crePrec),
                dI = Convert.ToDecimal(debInit), cI = Convert.ToDecimal(creInit);
            rulajDeb = (dC + dP).ToString();
            rulajCre = (cC + cP).ToString();
            totalDeb = (dC + dP + dI).ToString();
            totalCre = (cC + cP + cI).ToString();
            SoldPrecDeb = (dP + dI).ToString();
            SoldPrecCre = (cP + cI).ToString();



            return true;
        }

        public Boolean CalcTotal(String filtru,DateTime dst, DateTime ded, Int16 idJurnal,ModuleClass mi)
        {
            SqlCommand cmd = new SqlCommand("", mConn);
            Object obj = null;
            Int16 codValuta = 0; /*codValuta.ToString(),modelContabil= smodelContabil.ToString();*/
            String strValoare = string.Empty;
            if (codValuta == 0)
                strValoare = "f.ValoareLei";
            else
                strValoare = "f.ValoareValuta";


            ///daca a fost selectat un interval se calculeaza rulajul precedent
            Boolean bData1 = ded != null;
            //prima zi a lunii
            if(dst==DateTime.MinValue)
                dst = new DateTime(ded.Year, ded.Month, 1);

            Decimal dCalcPrec = Decimal.Zero, cCalcPrec = Decimal.Zero, dDebPrec = Decimal.Zero, dCrePrec = Decimal.Zero;

            if (bData1)
            {
                cmd.CommandText = "SELECT SUM(f.[ValoareLei]) FROM RulajeDoc"+mi.AnArhiva+" d JOIN Rulaje"+mi.AnArhiva+" f ON d.IDDocument=f.IDDocument JOIN [Conturi"+mi.AnArhiva+"] c ON f.[ContDebit]=c.[Cont]  AND c.[CodUnitate]=D.[CodUnitate]  WHERE " +
                    "d.DataDoc < @DataDoc AND ContCredit <> 'N/A' AND ContDebit <> 'N/A' AND c.[CodUnitate]=" + mi.CodUnitate.ToString() + " " + filtru;
                if (idJurnal != -1)
                    cmd.CommandText += " AND [IdJurnal]=" + idJurnal.ToString();
                cmd.Parameters.Add(new SqlParameter("DataDoc", dst));
                obj = cmd.ExecuteScalar();
                if (obj != null && obj!=DBNull.Value)
                    dCalcPrec = Convert.ToDecimal(obj);
            }

            cmd.CommandText = "SELECT SUM(DebitInitial) DebitInitial FROM [Conturi"+mi.AnArhiva+"] C " +
                "WHERE Terminal=1 AND Cont <>'N/A'  AND [CodUnitate]=" + mi.CodUnitate.ToString() + " " + filtru;

            obj = cmd.ExecuteScalar();
            if (obj != null && obj != DBNull.Value)
                debInit = Convert.ToDecimal(obj).ToString("N2");

            cmd.CommandText = "SELECT SUM(DebitPrecedent) DebitPrecedent  FROM [Conturi"+mi.AnArhiva+"]  c " +
                " WHERE Terminal=1 AND Cont <>'N/A'  AND [CodUnitate]=" + mi.CodUnitate.ToString() + " " + filtru;
            obj = cmd.ExecuteScalar();
            if (obj != null && obj != DBNull.Value)
                dDebPrec = Convert.ToDecimal(obj);
            dDebPrec += dCalcPrec;
            debPrec = dDebPrec.ToString("N2");


            if (bData1)
            {
                cmd.CommandText = "SELECT SUM(f.[ValoareLei]) FROM RulajeDoc"+mi.AnArhiva+" d JOIN Rulaje"+mi.AnArhiva+" f ON d.IDDocument=f.IDDocument  JOIN [Conturi"+mi.AnArhiva+"] c ON " +
                 " f.[ContCredit]=c.[Cont]  AND c.[CodUnitate]=D.[CodUnitate]  WHERE d.DataDoc < @DataDoc AND ContDebit <> 'N/A' AND ContCredit <> 'N/A'  AND c.[CodUnitate]=" + mi.CodUnitate.ToString() + " " + filtru;
                //cmd.Parameters.Add(new SqlParameter("DataDoc", ded));
                /// a fost adaugat deja in if-ul anterior
                /// 
                if (idJurnal != -1)
                    cmd.CommandText += " AND [IdJurnal]=" + idJurnal.ToString();

                obj = cmd.ExecuteScalar();
                if (obj != null && obj != DBNull.Value)
                    cCalcPrec = Convert.ToDecimal(obj);
            }

            cmd.CommandText = "SELECT SUM(CreditInitial) CreditInitial FROM [Conturi"+mi.AnArhiva+"]  C " +
                " WHERE Terminal=1 AND Cont <>'N/A'  AND [CodUnitate]=" + mi.CodUnitate.ToString() + " " + filtru;
            obj = cmd.ExecuteScalar();
            if (obj != null && obj != DBNull.Value)
                creInit = Convert.ToDecimal(obj).ToString("N2");

            cmd.CommandText = "SELECT SUM(CreditPrecedent) CreditPrecedent  FROM [Conturi"+mi.AnArhiva+"]  C " +
                " WHERE Terminal=1 AND Cont <>'N/A'  AND [CodUnitate]=" + mi.CodUnitate.ToString() + " " + filtru;

            obj = cmd.ExecuteScalar();
            if (obj != null && obj != DBNull.Value)
                dCrePrec = Convert.ToDecimal(obj);
            dCrePrec += cCalcPrec;
            crePrec = dCrePrec.ToString("N2");


            cmd.CommandText = "SELECT SUM(" + strValoare + ") totalDebit FROM RulajeDoc"+mi.AnArhiva+" D  JOIN Rulaje"+mi.AnArhiva+" F ON D.IDDocument=F.IDDocument JOIN Conturi"+mi.AnArhiva+" C ON  F.ContDebit=C.Cont  AND c.[CodUnitate]=D.[CodUnitate]  WHERE  C.Cont<>'N/A' AND C.Terminal=1  AND C.[CodUnitate]=" + mi.CodUnitate.ToString() + " " 
                + filtru;
            cmd.Parameters.Clear();
            cmd.CommandText += " AND D.DataDoc >= @DataDocStart";
            cmd.Parameters.Add(new SqlParameter("DataDocStart", dst));
            cmd.CommandText += " AND D.DataDoc <= @DataDocEnd";
            cmd.Parameters.Add(new SqlParameter("DataDocEnd", ded));

            obj = cmd.ExecuteScalar();
            if (obj != null && obj != DBNull.Value)
                debCurent = Convert.ToDecimal(obj).ToString("N2");


            cmd.CommandText = "SELECT SUM(" + strValoare + ") totalCredit FROM RulajeDoc" + mi.AnArhiva + " D  JOIN Rulaje" + mi.AnArhiva + " F ON D.IDDocument=F.IDDocument JOIN Conturi" + mi.AnArhiva + " C ON  F.ContCredit=C.Cont  AND c.[CodUnitate]=D.[CodUnitate]  WHERE  C.Cont<>'N/A' AND C.Terminal=1  AND C.[CodUnitate]=" + mi.CodUnitate.ToString() + " " 
                + filtru;
            cmd.Parameters.Clear();
            cmd.CommandText += " AND D.DataDoc >= @DataDocStart";
            cmd.Parameters.Add(new SqlParameter("DataDocStart", dst));
            cmd.CommandText += " AND D.DataDoc <= @DataDocEnd";
            cmd.Parameters.Add(new SqlParameter("DataDocEnd", ded));
            obj = cmd.ExecuteScalar();
            if (obj != null && obj != DBNull.Value)
                creCurent = Convert.ToDecimal(obj).ToString("N2");

            ///calcularea sumelor soldurilor finale
            ///nu este acelasi lucru cu sumele totale
            ///
         
            Decimal dC = Convert.ToDecimal(debCurent), dP = Convert.ToDecimal(debPrec), cC = Convert.ToDecimal(creCurent), cP = Convert.ToDecimal(crePrec),
                dI = Convert.ToDecimal(debInit), cI = Convert.ToDecimal(creInit);
            rulajDeb = (dC + dP).ToString();
            rulajCre = (cC + cP).ToString();
            totalDeb = (dC + dP + dI).ToString();
            totalCre = (cC + cP + cI).ToString();
            SoldPrecDeb = (dP + dI).ToString();
            SoldPrecCre = (cP + cI).ToString();



            return true;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="filtru"></param>
        /// <param name="filterDebit"></param>
        /// <param name="filterCredit"></param>
        /// <param name="dst"></param>
        /// <param name="ded"></param>
        /// <param name="jurnal"></param>
        /// <param name="soldinitalterminal">daca e true - atunci soldul initial se calculeaza prin insumare soldurilor initiale a conturilor terminale
        /// - daca e false atunci prin insumare soldurilor initiale a soldurilor care au parinte N/A</param>
        /// <returns></returns>
	    public Boolean CalcSume(String filtru,String filterDebit,String filterCredit,DateTime dst,DateTime ded,String jurnal,Boolean SoldInitalTerminal,ModuleClass mi)
	    {
            SqlCommand cmd = new SqlCommand("", mConn);
            Object obj=null;
		    Int16	codValuta=0; /*codValuta.ToString(),modelContabil= smodelContabil.ToString();*/
		    String	strValoare=string.Empty;
		    if (codValuta==0)
			    strValoare = "f.ValoareLei";
		    else
			    strValoare = "f.ValoareValuta";
            

            ///daca a fost selectat un interval se calculeaza rulajul precedent
		    Boolean bData1 = dst!=null;            
		    Decimal dCalcPrec= Decimal.Zero,cCalcPrec=Decimal.Zero;

            if (filterDebit != string.Empty)
            {
                filterDebit = " AND " + filterDebit;
            }
            String prefix = String.Empty;
            String filtruArhiva = String.Empty;
            String filtruArhivaC = String.Empty;
            if (mi.AnArhiva != String.Empty)
            {
                prefix = "arh";
                filtruArhiva = " AND d.An =c.An AND d.An=" + mi.AnArhiva;
                filtruArhivaC = " AND c.An=" + mi.AnArhiva;
            }
		    if(bData1){
                cmd.CommandText = "SELECT SUM(f.[ValoareLei]) FROM " + prefix + "RulajeDoc d JOIN " + prefix + "Rulaje f ON d.IDDocument=f.IDDocument JOIN [" + prefix + "Conturi] c ON f.[ContDebit]=c.[Cont]  AND c.[CodUnitate]=D.[CodUnitate]  WHERE " +
                    "d.DataDoc < @DataDoc AND ContCredit <> 'N/A'  " + filtruArhiva + " AND ContDebit <> 'N/A'  AND C.[CodUnitate]=" + mi.CodUnitate.ToString() + " " + filterDebit + filtru + (jurnal != "-1" ? (" AND [IDJurnal]=" + jurnal) : "");
                cmd.Parameters.Add(new SqlParameter("DataDoc",dst));
                obj = cmd.ExecuteScalar();
	    	    if(obj != null && obj!=DBNull.Value)                    
			        dCalcPrec = Convert.ToDecimal(obj);
		    }
            if (filterDebit != string.Empty)
            {
                filterDebit = filterDebit.Replace("ContDebit", "Cont");
            }
            cmd.CommandText = "SELECT SUM(DebitInitial) DebitInitial FROM [" + prefix + "Conturi] C " +
                    (SoldInitalTerminal ? "WHERE Terminal=1 AND Cont <>'N/A' " : "WHERE [ContParinte] = 'N/A' ") +
                     filtruArhivaC + " AND C.[CodUnitate]=" + mi.CodUnitate.ToString() + " " + filterDebit + filtru;
            
            obj = cmd.ExecuteScalar();
		    if(obj != null && obj!=DBNull.Value)
                debInit = Convert.ToDecimal(obj).ToString("N2");

            cmd.CommandText = "SELECT SUM(DebitPrecedent) DebitPrecedent  FROM [" + prefix + "Conturi]  c " +
                    "WHERE Terminal=1 AND Cont <>'N/A' " +
                     filtruArhivaC + "  AND C.[CodUnitate]=" + mi.CodUnitate.ToString() + " " + filterDebit + filtru;
            obj = cmd.ExecuteScalar();
            Decimal dDebPrec = Decimal.Zero;
		    if(obj != null && obj!=DBNull.Value)
                dDebPrec = Convert.ToDecimal(obj);
		    dDebPrec += dCalcPrec;
            debPrec = dDebPrec.ToString("N2");


            if (filterCredit != string.Empty)
            {
                filterCredit = " AND " + filterCredit;
            }
		    if(bData1){
                cmd.CommandText = "SELECT SUM(f.[ValoareLei]) FROM " + prefix + "RulajeDoc d JOIN " + prefix + "Rulaje f ON d.IDDocument=f.IDDocument  JOIN [" + prefix + "Conturi] c ON f.[ContCredit]=c.[Cont]  AND c.[CodUnitate]=D.[CodUnitate]  WHERE " +
                "d.DataDoc < @DataDoc AND ContDebit <> 'N/A' " + filtruArhiva + " AND ContCredit <> 'N/A'  AND C.[CodUnitate]=" + mi.CodUnitate.ToString() + " " + filterCredit + filtru + (jurnal != "-1" ? (" AND [IDJurnal]=" + jurnal) : "");
                //cmd.Parameters.Add(new SqlParameter("DataDoc", ded));
                /// a fost adaugat deja in if-ul anterior
                obj = cmd.ExecuteScalar();
                if (obj != null && obj!=DBNull.Value)                    
                    cCalcPrec = Convert.ToDecimal(obj);
		    }
            if (filterCredit != string.Empty)
            {
                filterCredit = filterCredit.Replace("ContCredit", "Cont");
            }


            cmd.CommandText = "SELECT SUM(CreditInitial) CreditInitial FROM [" + prefix + "Conturi]  C " +
                    (SoldInitalTerminal ? "WHERE Terminal=1 AND Cont <>'N/A' " : "WHERE [ContParinte] = 'N/A' ") +
                    filtruArhivaC + "  AND C.[CodUnitate]=" + mi.CodUnitate.ToString() + " " + filterCredit + filtru;
            obj = cmd.ExecuteScalar();
		    if(obj == null)
			    return false;
            creInit = Convert.ToDecimal(obj).ToString("N2");

            cmd.CommandText = "SELECT SUM(CreditPrecedent) CreditPrecedent  FROM [" + prefix + "Conturi]  C " +
                    " WHERE Terminal=1 AND Cont <>'N/A' " + filtruArhivaC + " AND C.[CodUnitate]=" + mi.CodUnitate.ToString() + " " + filterCredit + filtru;

            obj = cmd.ExecuteScalar();
		    if(obj == null)
			    return false;


		    Decimal dCrePrec = Convert.ToDecimal(obj);
		    dCrePrec += cCalcPrec;
		    crePrec = dCrePrec.ToString("N2");


            cmd.CommandText = "SELECT SUM(" + strValoare + ") totalDebit FROM " + prefix + "RulajeDoc D  JOIN " + prefix + "Rulaje F ON D.IDDocument=F.IDDocument JOIN " + prefix + "Conturi C ON  F.ContDebit=C.Cont  AND c.[CodUnitate]=D.[CodUnitate]  WHERE C.Terminal=1 AND C.Cont<>'N/A' " + filtruArhiva + " AND C.[CodUnitate]=" + mi.CodUnitate.ToString() + " " 
                + (filterDebit != String.Empty ? filterDebit : (filterCredit != String.Empty ? filterCredit : "")) + filtru + (jurnal != "-1" ? (" AND [IDJurnal]=" + jurnal) : "");
            cmd.Parameters.Clear();
            if (dst != null)
            {
                cmd.CommandText += " AND D.DataDoc >= @DataDocStart";
                cmd.Parameters.Add(new SqlParameter("DataDocStart", dst));
            }
            if (ded != null)
            {
                cmd.CommandText += " AND D.DataDoc <= @DataDocEnd";
                cmd.Parameters.Add(new SqlParameter("DataDocEnd", ded));
            }

            obj = cmd.ExecuteScalar();
		    if(obj != null && obj!=DBNull.Value)			    
                debCurent = Convert.ToDecimal(obj).ToString("N2");


            cmd.CommandText = "SELECT SUM(" + strValoare + ") totalCredit FROM " + prefix + "RulajeDoc D  JOIN " + prefix + "Rulaje F ON D.IDDocument=F.IDDocument JOIN " + prefix + "Conturi C ON  F.ContCredit=C.Cont AND c.[CodUnitate]=D.[CodUnitate]  WHERE  C.Terminal=1  AND C.Cont<>'N/A' " + filtruArhiva + " AND C.[CodUnitate]=" + mi.CodUnitate.ToString() + " " 
                + (filterDebit != String.Empty ? filterDebit : (filterCredit != String.Empty ? filterCredit : "")) + filtru + (jurnal != "-1" ? (" AND [IDJurnal]=" + jurnal) : "");

            cmd.Parameters.Clear();
            if (dst != null)
            {
                cmd.CommandText += " AND D.DataDoc >= @DataDocStart";
                cmd.Parameters.Add(new SqlParameter("DataDocStart", dst));
            }
            if (ded != null)
            {
                cmd.CommandText += " AND D.DataDoc <= @DataDocEnd";
                cmd.Parameters.Add(new SqlParameter("DataDocEnd", ded));
            }


            obj = cmd.ExecuteScalar();
		    if(obj != null && obj!=DBNull.Value)
                creCurent = Convert.ToDecimal(obj).ToString("N2");

		    Decimal dC = Convert.ToDecimal(debCurent), dP = Convert.ToDecimal(debPrec),cC = Convert.ToDecimal(creCurent) ,cP = Convert.ToDecimal(crePrec),
			    dI = Convert.ToDecimal(debInit),cI = Convert.ToDecimal(creInit);
		    rulajDeb = (dC + dP).ToString("N2");
            rulajCre = (cC + cP).ToString("N2");
            totalDeb = (dC + dP + dI).ToString("N2");
            totalCre = (cC + cP + cI).ToString("N2");
            SoldPrecDeb = (dP + dI).ToString("N2");
            SoldPrecCre = (cP + cI).ToString("N2");
        
		    return true;
	    }
        
    }

    [Serializable]
    public class FisaContSolduri
    {
        public FisaContSolduri(Decimal soldInitial, DateTime dataSold)
        {
            _SoldInitial = soldInitial;
            _DataSold = dataSold;
        }

        private Decimal _SoldInitial = Decimal.Zero;
        [System.ComponentModel.Bindable(true)]
        public Decimal SoldInitial
        {
            get
            {
                return _SoldInitial;
            }
            set
            {
                _SoldInitial = value;
            }
        }
        private DateTime _DataSold = DateTime.MinValue;
        [System.ComponentModel.Bindable(true)]
        public DateTime DataSold
        {
            get
            {
                return _DataSold;
            }
            set
            {
                _DataSold = value;
            }
        }
    }
    
}

